doudou0111 2010-11-16 02:08 采纳率: 0%
浏览 102
已采纳

正则表达式替换&符号而不是html实体

In the code below I want to replace plain ampersands with "and" while ignoring the ampersands that are being used as part of an html entities (ex: ")

I've tested my expression &(?!([\w ]{2,7}|#[\d]{1,4});) over at http://www.gskinner.com/RegExr/ and it matches what I want.

However, when I run this code, the results are blank.

$content = "" Apples & Oranges "";
$content = preg_replace("/&(?!([\w
]{2,7}|#[\d]{1,4});)/g","and",$content); 

echo $content;

Is my approach flawed somehow or do I just have a syntax issue?

  • 写回答

3条回答 默认 最新

  • dousuiben8395 2010-11-16 02:13
    关注

    Remove the g flag and it should work fine.

    Note that it seem to me that you'd expect and ampersand to be surrounded spaces, so the following could be a simplified solution:

    $content = preg_replace("/\s/&\s/"," and ",$content); 
    

    Although I realise that this might allow mistyped text to cause encoding errors. If there is a space missing.

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

报告相同问题?

悬赏问题

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