Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php正则表达式和或(|)_Php_Regex - Fatal编程技术网

php正则表达式和或(|)

php正则表达式和或(|),php,regex,Php,Regex,我正在试验php中的|(or)和正则表达式的问题 下面是我想做的,例如我有这三句话: “苹果好吃” “一天一苹果,医生远离我” “我喜欢吃苹果” 我想把苹果这个词改成橙色,下面是我的代码: $oldWord="apple"; $newWord="orange"; $text = preg_replace('#^' . $oldWord . ' #', $newWord, $text); $text = preg_replace('# ' . $oldWord . ' #', $newWord,

我正在试验php中的|(or)和正则表达式的问题

下面是我想做的,例如我有这三句话:

“苹果好吃”

“一天一苹果,医生远离我”

“我喜欢吃苹果”

我想把苹果这个词改成橙色,下面是我的代码:

$oldWord="apple";
$newWord="orange";
$text = preg_replace('#^' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . '$#', $newWord, $text);
当然它可以工作,但我还没有找到正确的组合,只需要一行关键字为|(or)的代码就可以做到这一点


你们有什么建议吗?谢谢

为什么不干脆
str_replace('apple','orange','text')

编辑: 根据用户的评论:

preg_replace('/\bapple\b/', 'orange', $text);
如果您担心在表达式中正确转义搜索词:

$oldWord = preg_quote($oldWord, '/');
$text = preg_replace("/\b$oldWord\b/", $newWord, $text);

请注意,您的正则表达式删除了
apple
周围的空格。如果这不是您想要的,而是您只想替换
apple
,如果它是完整的单词,那么,正如其他一些人建议的那样,使用单词边界:

$text = preg_replace('#\b' . $oldWord . '\b#', $newWord, $text);
如果您也打算删除空格,那么您可以要求使用wordboundary,但空格是可选的:

$text = preg_replace('#[ ]?\b' . $oldWord . '\b[ ]?#', $newWord, $text);

如果它们在那里,它们也将被移除。如果不是,正则表达式也不在乎。请注意,
[]
完全等同于只键入一个空格,但我发现它在正则表达式中更可读。

只需使用
preg\u replace
而不是
preg\u match

preg_replace('⁓\b'.$oldWord.'\b⁓', $newWord, $text)
我不能测试,但是

$text = preg_match('#\b' . $oldWord . '\b#ig', $newWord, $text);

应该拯救你的一天;)

因此,如果您只想替换整个单词,也就是说,不要使用“菠萝”,那么
stru-replace
方法将无法工作。您应该使用的是单词边界锚
\b

preg_replace('#\b' + $oldWord + '\b#', $newWord, $text)

“当然行”
?preg_match不会取代任何东西。所以换句话说,
$oldWord
可以在任何地方?那么,为什么要使用
^
$
呢?我猜你这样做是为了防止匹配“apple”只是单词的一部分,比如“Snapple”?如果是这样,您可能需要:
\bapple\b#
注意,您的代码会吞没目标单词两侧的空格。例如,使用
$text='a apple a day'
运行代码会产生
'Anorangea day'
。你想保留空格吗?如果你显示了你得到的结果和你想要得到的结果,这会很有帮助。因为我只想删除单独使用的“apple”,例如,我不想从评论部分删除“Anaple”漂亮的复制/粘贴;-)@peeHaa,你知道,我10分钟前就回答了,两分钟后在那里贴出了类似的评论。。。你确定是我抄的吗?@user1836529删掉它
preg_replace
是默认全局的,但与字符串“apple”
不匹配。这要求它两边都有空格。@nickf抱歉,完全忽略了它在
“菠萝”
中匹配的内容,我想这不是OP想要的。谢谢,我试过了,但我得到了错误解析错误:语法错误,意外的T_ECHO@user1836529然后加一个分号<代码>$text=preg\u replace('\\b'+$oldWord+'\b\\,$newWord,text)