1

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

4

4 回答 4

4
preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$1', $string);

这个想法是匹配并捕获每次匹配之前的任何内容,然后将其重新插入。 (?:^.*?test)?导致第一个实例test被包含在捕获中。(所有\bs 都是为了避免部分单词匹配,例如testinsmartesttestify.)

于 2010-05-17T20:56:58.453 回答
3

简单的PHP方式:

<?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];
?>

会给你“AN”。

更新:不知道这是一个替换。尝试这个:

<?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;
?>

找到第一个匹配并记住它的位置,然后删除所有内容,然后将第一个位置的所有内容放回原处。

于 2010-05-17T15:10:45.823 回答
0

假设 'blah' 是您的正则表达式模式,blah(blah) 将匹配并捕获第二个

于 2010-05-17T15:10:35.573 回答
0

迟到的答案,但它可能对人们有用。

$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 
于 2015-06-25T14:43:06.423 回答