PHP preg_match一次两个东西


php preg_match two things in one time

hello是否可以使用一个preg_match匹配两个东西?例如我有一个:

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

和我想匹配url (http://google.com)和文本(Google)

有可能这样做吗?例如:

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

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

现在完成了谢谢

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

当然可以

  preg_match('/^<a href="(?<url>.*?)">(?<anchor>.*?)</a>/',$yourtext,$matches);
  echo 'Url is : ' . $matches['url'] . ' , and text is : ' . $matches['anchor'] ;

这是命名子模式出现的地方

示例直接取自PHP文档

<?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
)

是的,这是可能的-只需传递第三个参数 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()

这个请求是可以实现的。只需将$matches数组传递到函数调用中。

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

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

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

你可以这样做:

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

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