php preg_match一次两件事

时间:2011-04-09 16:05:00

标签: php

你好可以使用一个preg_match匹配两件事吗? 例如,我有一个:

<a href="http://google.com">Google</a>

我希望匹配网址(http://google.com)和文字(Google)

可以做那样的事吗?类似的东西:

preg_match('/^<a href="(.*?)">(.*?)</a>/', $source, $match)

然后

echo 'Url is : ' . $match[1] . ' , and text is : ' . $match[2];

现在完成,谢谢

*我会在几分钟内接受答案

5 个答案:

答案 0 :(得分:2)

当然是

  preg_match('/^<a href="(?<url>.*?)">(?<anchor>.*?)</a>/',$yourtext,$matches);

  echo 'Url is : ' . $matches['url'] . ' , and text is : ' . $matches['anchor'] ;

答案 1 :(得分:2)

这是一个名为subpatterns的地方

直接从php docs

获取的示例
<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however 
 * the above form is recommended for backwards compatibility */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

结果

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

答案 2 :(得分:1)

是的,可以 - 只需将第三个参数传递给preg_match()

$str = '<a href="http://google.com">Google</a>';
if (preg_match('#<a href="(.*?)">(.*?)</a>#', $str, $matches)) {
    var_dump($matches);
}

这是$matches数组:

array
  0 => string '<a href="http://google.com">Google</a>' (length=38)
  1 => string 'http://google.com' (length=17)
  2 => string 'Google' (length=6)

第一场比赛在$matches[1],第二场比赛在$matches[2]


注意:不确定你正在尝试做什么...但是以防万一:正则表达式非常适用于简单的提取,但是它们无法在不花费更多精力的情况下处理语法HTML变体。

相反,特别是对于比这个更复杂的情况,或者速度无关紧要(输入而不是输出处理),您可能想要使用XML解析器。
例如,在PHP中,您可以使用DOMDocument::loadHTML()

答案 3 :(得分:0)

你可以用这个:

preg_match("/^<a href=\"(.*?)\">(.*?)</a>/", $string, $matches);

$ matches将包含数组中匹配的模式。

答案 4 :(得分:0)

可以实现此请求。只需将$ matches数组传递给函数调用。

preg_match('/^<a href="(.*?)">(.*?)</a>/', '<a href="http://google.com">Google</a>', $matches);

然后,通过相关数字索引访问匹配文本!

echo $matches[1]; //"http://google.com"
echo $matches[2]; //"Google"