【问题标题】:preg_match and preg_replace in string php字符串 php 中的 preg_match 和 preg_replace
【发布时间】:2013-08-13 11:39:07
【问题描述】:

$string = "Lorem Ipsum is #simply# dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard #dummy# text ever since the 1500s, when an unknown printer took a galley of #type1# and scrambled it to #make# a #type2# specimen book. It has survived not only #five# centuries, but also the #leap# into electronic typesetting, remaining essentially unchanged";

我有一组硬编码词,例如"#simply# | #dummy# | #five# | #type1#"

我期望的输出是:

  1. 如果在$string 中找到硬代码字,它应该以黑色突出显示。喜欢"<strong>...</strong>"

  2. 如果$string 中的单词在#...# 内,但在硬编码单词列表中不可用,则字符串中的这些单词应以红色突出显示。

  3. 请注意,即使我们在硬编码字中包含#type1#,如果 $string 包含#type2##type3#,它也应该被突出显示。

为此,我尝试如下

$pattern = "/#(\w+)#/";

$replacement = '<strong>$1</strong>';

$new_string = preg_replace($pattern, $replacement, $string);

这让我将 #..# 标记内的所有单词都突出显示。

我的怀孕很糟糕_有人可以帮忙吗?提前致谢。

【问题讨论】:

    标签: preg-replace preg-match preg-match-all


    【解决方案1】:

    您必须使用将回调函数作为替换参数的preg_replace_callback。在函数中可以测试哪个捕获组成功并根据返回字符串。

    $pattern = '~#(?:(simply|dummy|five|type[123])|(\w+))#~';
    $replacement = function ($match) {
        if ( empty($match[2]) )
            return '<strong>' . $match[1] . '</strong>';
        else
            return '<strong style="color:red">' . $match[2] . '</strong>';
    };
    
    $result = preg_replace_callback($pattern, $replacement, $text);
    

    【讨论】:

      【解决方案2】:

      不确定我是否真的了解您的需求,但是:

      $pat = '#(simply|dummy|five|type\d)#';
      $repl = '<strong>$1</strong>';
      $new_str = preg_replace("/$pat/", $repl, $string);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多