preg_match从字符串中删除不需要的文本

时间:2016-07-30 18:39:46

标签: php regex preg-match

我想从字符串中删除不需要的文字。

$description = 'this is some huge text <a href="http://example.com/dynamicID">dynamicID</a><br> and some more text here';

preg_match('/(example.com([^&]*)?)"/',$description,$matches);

$part = $matches[1];

echo $part; //returning example.com/dynamicID">dynamicID</a><br> and...

但我只想要(example.com/dynamicID)并从字符串中删除其余文本。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

你很亲密。我假设您想要获取文本的URL部分(在<a>标记的结束引号之前的a.k.a。

您需要做的就是在?"之后添加),以确保您在引用之前尽可能快地匹配任何字符。

这样做,结果$ matches [0]也将包含引号字符。您可以通过将组添加到您实际想要匹配的内容并将$ matches [1]作为结果来解决此问题。下面是您使用上面提到的2个更改修改的代码:

$description = 'this is some huge text <a href="http://example.com/dynamicID">dynamicID</a><br> and some more text here';

preg_match('/(example.com([^&]*)?)"/',$description,$matches);

var_dump($matches);

输出如下:

array(3) {
  [0]=>
  string(22) "example.com/dynamicID""
  [1]=>
  string(21) "example.com/dynamicID"
  [2]=>
  string(10) "/dynamicID"
}
相关问题