Php 替换为preg_仅当有更多匹配项时才替换

Php 替换为preg_仅当有更多匹配项时才替换,php,preg-replace,expression,Php,Preg Replace,Expression,仅当存在多个匹配文本时,我才希望替换文本。如果有一个匹配的元素,我不想替换。可能吗?试试看 $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] )

仅当存在多个匹配文本时,我才希望替换文本。如果有一个匹配的元素,我不想替换。可能吗?

试试看

$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替换。

确定。使用preg_match_all确保count$matches[1]大于或等于2。这可能会有所帮助