Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there anyway to skip the first match when using regex and php.

Or is there some way of achieveing this using str_replace.

Thanks

UPDATE I am trying to remove all the instances of a string from another string but I want to retain the first occurance e.g

$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';

Ouput string would be:

This is a test string to test to removing the word test

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

preg_replace('/((?:^.*?test)?.*?)test/', '$1', $string);

The idea is to match and capture whatever precedes each match, and plug it back in. (?:^.*?test)? causes the first instance of test to be included in the capture. (All the s are to avoid partial-word matches, like the test in smartest or testify.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...