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条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持