dongyiyu3953 2012-11-19 17:39
浏览 25
已采纳

php正则表达式和或(|)

I am experimenting a problem with | (or) and the regex in php.

Here is what I would like to do, for example I have those 3 sentences :

"apple is good to eat"

"an apple a day keeps the doctor away"

"i like to eat apple"

And lets say that i would like to change the word apple by orange, so here is my code :

$oldWord="apple";
$newWord="orange";
$text = preg_replace('#^' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . '$#', $newWord, $text);

Of course it works but i haven't found the right combinaison to do that with only one line of code with the key word | (or).

Do you guys have any suggestion please ? thanks

  • 写回答

5条回答 默认 最新

  • douwei1950 2012-11-19 17:43
    关注

    Note that your regex removes the spaces around apple. If this is not what you desire, but instead you just want to replace apple if it's the full word, then, as some others recommended, use word boundaries:

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

    If you did intent to remove the spaces, too you could require a wordboundary, but make the spaces optional:

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

    If they are there, they will be removed, too. If they are not, the regex doesn't care. Note that [ ] is completely equivalent to just typing a space, but I find it more readable in a regex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了