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)

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了