在PHP中使用preg_replace时如何找到匹配项?

时间:2020-03-05 18:37:38  来源:igfitidea点击:

我正在尝试抓住几个单词的大写字母,然后将它们包裹在span标签中。我正在使用preg_replace进行提取和包装,但未输出任何内容。

preg_replace("/[A-Z]/", "<span class=\"initial\"></span>", $str)

解决方案

回答

我们需要将模式放在括号/([[A-Z])/中,如下所示:

preg_replace("/([A-Z])/", "<span class=\"initial\"></span>", $str)

回答

从php.net上的preg_replace文档中:

replacement  may contain references of
  the form \n or (since PHP 4.0.4) $n,
  with the latter form being the
  preferred one. Every such reference
  will be replaced by the text captured
  by the n'th parenthesized pattern.

请参阅Flubba的示例。

回答

\ 0也将匹配整个匹配的表达式,而无需使用括号进行显式捕获。

preg_replace("/[A-Z]/", "<span class=\"initial\">\0</span>", $str)

与往常一样,我们可以转到php.net/preg_replace或者php.net/ <任何搜索词>来快速搜索文档。查阅文档:

##代码## or ##代码## refers to the text matched by the whole pattern.

回答

在所需的捕获位置周围使用括号。