0

我如何调节正则表达式以检查匹配项中是否存在字符串以不重复它

这是我想要的一个例子(错误代码)

$string = "1234";
$replacement = "/$1(5?)/"; // this should check if "5" is in $string, if not then add it with $1 
preg_replace('/(.*)/', $replacement, $string);

有什么好的建议$replacement
我只想使用preg_replace一行代码没有其他功能

4

2 回答 2

3
preg_replace('/^([^5]*)$/', '${1}5', '1253'); # => 1253
preg_replace('/^([^5]*)$/', '${1}5', '1234'); # => 12345

注意:用于${1}5而不是与5`$15区分开group 1来。literal

于 2013-07-28T09:11:14.053 回答
0

你可以使用 strpos()

if( strpos($string, $keyword) === false) {
 $string = $string. $keyword;
}
于 2013-07-28T09:11:59.763 回答