替换单词IF的第一个和最后一个出现

时间:2013-12-21 20:14:23

标签: php regex

通过这种代码的平衡,我将替换字符串中单词的第一个和最后一个出现。

    $text = 'A United States aircraft fly in United States in the United States area.';
    $find = 'United States';
    $replace = ' U.S ';

    $firsto =  preg_replace("/$find/", "$replace", $text, 1); // stolen in stackoverflow 

    $lasto = preg_replace(strrev("/$find/"),strrev($replace),strrev($firsto),1); // stolen in stackoverflow 

    $final = strrev($lasto);

    echo "<br><br> $final"; 

在此示例中,单词United States出现3次,下面的代码替换第一次和最后一次出现。

   And Output: A U.S aircraft fly in United States in the U.S area.

我的问题是if word = 2的出现是这样的:

         $text = 'A United States aircraft fly in United States';

使用i want to replace only the first occurrence if there are only 2 occurrences上方代码的修改版本并输出类似内容。

     Output: A U.S aircraft fly in United States.

其他if occurrence > 2使用以下代码。感谢

2 个答案:

答案 0 :(得分:0)

if (substr_count($text,$find) == 2){
    $firsto =  preg_replace("/$find/", "$replace", $text, 1);
}
else{
    ... use existing
}

答案 1 :(得分:0)

$firsto =  preg_replace("/$find/", "$replace", $text, 1); // outputs '123def abcdef abcdef'

$final = $firsto;
$m;
if(preg_match_all("/($find)/",$firsto, $m) && count($m[1]) > 1){
    $lasto = preg_replace(strrev("/$find/"),strrev($replace),strrev($firsto),1);
    $final = strrev($lasto);
}