仅当存在更多匹配项时才替换preg_replace

时间:2013-12-30 11:00:17

标签: php preg-replace expression

我想仅在匹配文本超过1时才替换文本。如果有一个匹配的元素,我不想替换。有可能吗?

1 个答案:

答案 0 :(得分:0)

尝试

$subject = 'This is the text in which we will perform replacements';
$pattern = '/\si[ns]\s/';
$replace = ' XX ';

if( preg_match_all( $pattern , $subject , $matches )
    && isset( $matches[0] )
    && count( $matches[0] )>=2 ){

  $subject = preg_replace( $pattern , $replace , $subject );

}else{

  #echo 'Not Enough Matches';

}

(将用“XX”代替“in”和“is”。)