开发者

php preg_match -> save matched value in variable?

my $conten开发者_StackOverflow社区t variable stores a youtube video link.

$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

How can I store the value of the matched string in a variable? Now if I print_r($video) I'm just getting printed a 1 which means it's found. However i need to hold the found string in a variable. How can i do this?

Thank you


You should find it in $found[2]

That contains all the captured matches, which is all the patterns you've got in parentheses.

  • $found[0] = entire match
  • $found[1] = 1st expression [TRACK=
  • $found[2] = entire URL, which you have a number of sub-groups in - these will form following captured matches:
  • $found[3] = http or https
  • $found[4] = separator ://
  • $found[5] = subdomain
  • $found[5] = .youtube.
  • $found[6] = top level domain
  • $found[7] = path
  • $found[8]= closing ]

Clearly, you're using parentheses in a fairly wasteful way, as you're capturing data you have no intention of using. You can use (?: ) as a way of grouping a pattern without capturing, e.g. (?:http|https) matches http or https, but doesn't capture it.


use preg_filter - if you want to use it with multiple links (will return only correct).

or use preg_replace, to take what you need from $content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜