doupin5667 2014-05-28 23:00
浏览 39
已采纳

preg_replace php需要替换一个尚未包含在元素中的字符串

I need to be able to replace a string with what would be wrapped in a sort of BBcode style element, but only if that string is not already wrapped in the element.

Example:

The fox runs really fast through Sudan, but also runs really fast through [country]Canada[/country]

Loopping through a list of all the countries I want to replace and wrap in this country brackets I tried this

$replace = preg_replace("#(?<!\[country(.)\])". preq_quote($country) ."(?!\[/country\])#", "[country]{$country}[/country]", $replace);

Expected output:

The fox runs really fast through [country]Sudan[country], but also runs really fast through [country]Canada[/country]

But Im actually getting

Actual output:

The fox runs really fast through [country]Sudan[country], but also runs really fast through [country][country]Canada[/country][/country]

If its already wrapped, I dont want to re-wrap it.

  • 写回答

1条回答 默认 最新

  • douzinei6926 2014-05-28 23:13
    关注

    It's easy, you can use the (*SKIP)(*FAIL) trick to skip all that you want in a string:

    $listOfCountries = array('France', 'Soudan', 'Quatar', 'China', 'Zimbabwe');
    
    $pattern '~\[country][^[]+\[/country](*SKIP)(*FAIL)|\b(?i:'
           . implode('|', $listOfCountries) . ')\b~';
    
    $result = preg_replace($pattern, '[country]$0[/country]', $text);
    

    (*SKIP) forbids to retry a substring when the pattern fails later, and (*FAIL) forces the regex engine to fail.

    Note: if you are sure that the list of countries only contains letters and spaces, you don't need to use preg_quote. However if your list contains abbr like R.D.C. ("République Démocratique du Congo"), it is better to use preg_quote. Be careful, if you have abbr in the list \b will no more work, you must replace it with an other kind of boundary (since the dot is not in \w), example:(?=\s|[^\PP.]) (a white character or a punctuation character that is not a dot)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值