【问题标题】:preg_match and preg_replace in phpphp 中的 preg_match 和 preg_replace
【发布时间】:2013-08-01 08:08:12
【问题描述】:

我的任务是查找和替换以“#”开头和结尾的单词。

示例 - 我的字符串如下所示:

举起双手参加#performer1#,举起双手参加#event#。

我期望的输出是:

#performer1# 举起双手,#event# 举起双手。

我对php中的正则表达式一无所知,而且我是初学者,有人可以帮忙吗?

【问题讨论】:

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


    【解决方案1】:

    正如您已经建议的那样,preg_replace function 应该可以解决问题。你现在需要的是这样的正则表达式

    $string = "Put your hands up in the air for #performer#, ...";
    $pattern = "/#(\w+)#/";
    $replacement = '<strong>$1</strong>';
    $new_string = preg_replace($pattern, $replacement, $string);
    

    魔术位是$pattern 变量,您可以在其中指定要查找的内容。如果你把括号括起来,你可以引用$replacement变量中的实际内容。

    \w+ 基本上是说:匹配尽可能多的字符(至少一个),它们是 a-z、A-Z、0-9 或 _。

    PHP PCRE Pattern Syntax 可以为您提供更多关于如何使用正则表达式的提示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2011-04-23
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多