2

我刚开始使用 PHP 正则表达式。我了解如何阅读和编写它们(尽管我需要我的书,因为我没有记住任何模式符号)。我真的很想在我的网站上使用 RegExp 进行 BB 代码,使用preg_replace.

我了解参数,但我不明白的是什么定义了模式中要替换的内容?到目前为止我所拥有的:

preg_replace('/(\[url=http:\/\/.*\])/','<a href="$1">$2</a>',"[url=http://google.com]");

现在,我知道这可能不是最好的“安全”方式,我只是想让一些东西工作。我匹配整个字符串......所以我得到一个看起来像mysite/[url=http://google.com].

我阅读了关于它的 PHP 手册,但我仍然对试图吸收和理解一些东西感到头疼:

  • 什么定义了由于模式而在字符串中替换的内容?
  • 什么告诉我我的 1 美元和 2 美元等等是什么?

我什至不知道他们叫什么。有人可以向我解释一下吗?

4

1 回答 1

3

相同的替换没有错误:

$BBlink = '[url=http://google.com]';

$pattern = '~\[url=(http://[^] ]+)]~';
$replacement = '<a href="$1">$1</a>';
$result = preg_replace($pattern, $replacement, $BBlink);

解释:

1) 图案

~       # pattern delimiter
\[      # literal opening square bracket
url=
(       # first capturing group
http://
[^] ]+  # all characters that are not ] or a space one or more times
)       # close the capturing group
]       # literal closing square bracket
~       # pattern delimiter

2) 更换

$1参考第一个捕获组

替代方案:http ://www.php.net/manual/en/function.bbcode-create.php ,见第一个例子。

于 2013-06-22T05:30:28.543 回答