使用php从字符串中识别模式

时间:2012-10-14 20:58:11

标签: php preg-replace preg-match

假设我有一个这样的字符串:

$string = 'Lorem Ipsum available, <a href="##article-6##">but the majority</a> have suffered alteration in some form, by injected humour.';

注意<a href="##article-6##">but the majority</a>

使用这个我想根据数据库中的id来链接我的文章。

现在,如何在该字符串上执行preg_replace以查看我是否有类似##article-6##的内容并仅提取该数字?

这个想法是好的吗?我能以更好的方式做到吗?

编辑:

我是这样做的:

$post_content = preg_replace_callback('/##article-(\d+)##/', function($matches){$args = explode(',', $matches[1]); // separate the arguments
return call_user_func_array('article_seo_url', $args); /* pass the arguments to article_seo_url function*/ }, $post_content);

使用此代码我也可以替换多个网址

3 个答案:

答案 0 :(得分:1)

如果你想要preg_replace,你需要使用/##article-(\d+)##/这样的正则表达式,并执行以下操作:

$string = 'Lorem Ipsum available, <a href="##article-6##">but the majority</a> have suffered alteration in some form, by injected humour.';
$string = preg_replace('/##article-(\d+)##/', 'link/to/article/with/id/$1.html', $string);

会导致$ string为:

Lorem Ipsum available, <a href="link/to/article/with/id/6.html">but the majority</a> have suffered alteration in some form, by injected humour.

答案 1 :(得分:0)

如果ID总是3位数,则甚至不需要正则表达式。

$string = 'Lorem Ipsum available, <a href="##article-6##">but the majority</a> have suffered alteration in some form, by injected humour.';
$start = strpos($string, 'article-');
$articleId = substr ( $string , intval($start)+8 , 3 );

答案 2 :(得分:0)

如果您的href存储在如下变量中:

$href="http://www.domain.com";

您可以直接将其插入字符串中,如下所示:

$string = "Lorem Ipsum available, <a href=\"$href\">but the majority</a> have suffered alteration in some form, by injected humour.";

请注意,重要的是要么逃避文字引号,要么使用其他类型,在这种情况下单打。