问题
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
回答1:
Easy PHP way:
<?php
$pattern = "/an/i";
$text = "banANA";
preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
preg_match($pattern, $text, $matches, 0, $matches[0][1]);
echo $matches[0];
?>
will give you "AN".
UPDATE: Didn't know it was a replace. Try this:
<?php
$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';
preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE);
$newString = preg_replace("/$toRemove/", "", $string);
$newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0);
echo $newString;
?>
Find the first match and remember where it was, then delete everything, then put whatever was in the first spot back in.
回答2:
preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$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 \b
s are to avoid partial-word matches, like the test
in smartest
or testify
.)
回答3:
assume 'blah' is your regex pattern, blah(blah) will match and capture the second one
回答4:
Late answer but it might be usefull to people.
$string = "This is a test string to test something with the word test and replacing test";
$replace = "test";
$tmp = explode($replace, $string);
$tmp[0] .= $replace;
$newString = implode('', $tmp);
echo $newString; // Output: This is a test string to something with the word and replacing
来源:https://stackoverflow.com/questions/2850092/how-to-skip-first-regex-match