php preg_match - >在变量中保存匹配的值?

问题描述 投票:4回答:2

我的$content变量存储了youtube视频链接。

$youtubeurl = "/(\[TRACK=)((http|https)(\:\/\/)(www|it|co\.uk|ie|br|pl|jp|fr|es|nl|de)(\.youtube\.)(com|it|co\.uk|ie|br|pl|jp|fr|es|nl|de)([a-zA-Z0-9\-\.\/\?_=&;]*))(\])/si"; 


$video = preg_match($youtubeurl, $content , $found);
print_r($video); // 1

如何将匹配字符串的值存储在变量中?现在如果我print_r($video)我只是打印一个1,这意味着它被发现。但是我需要在变量中保存找到的字符串。我怎样才能做到这一点?

谢谢

php preg-match
2个回答
4
投票

你应该在$found[2]找到它

它包含所有捕获的匹配,这是您在括号中得到的所有模式。

  • $ found [0] =完整匹配
  • $ found [1] =第一个表达式[TRACK =
  • $ found [2] =整个网址,您有多个子网 - 这些将形成以下捕获的匹配:
  • $ found [3] = http或https
  • $ found [4] = separator://
  • $ found [5] =子域名
  • $ found [5] = .youtube。
  • $ found [6] =顶级域名
  • $ found [7] =路径
  • $ found [8] =关闭]

显然,您正在以相当浪费的方式使用括号,因为您正在捕获您无意使用的数据。您可以使用(?: )作为一种分组模式而无需捕获的方法,例如(?:http|https)匹配http或https,但不捕获它。


1
投票

使用preg_filter - 如果你想使用多个链接(只返回正确)。

或者使用preg_replace,从$content获取你需要的东西。

© www.soinside.com 2019 - 2024. All rights reserved.