Php preg_match & # 8594; keep matching value in variable?

My $content variable stores a link to a YouTube video.

 $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 save the value of a matched string in a variable? Now, if I print_r($video) I just get 1 which means it is found. However, I need to keep the found string in a variable. How can i do this?

thanks

+4
source share
2 answers

You must find it in $found[2]

This contains all the captured matches, which are all the patterns that you have in parentheses.

  • $ found [0] = full match
  • $ found [1] = 1st expression [TRACK =
  • $ found [2] = the entire URL where you have several subgroups: they will be formed after the following 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] = close]

Obviously, you are using parentheses in a rather wasteful manner, since you are capturing data that you do not intend to use. You can use (?: ) As a way to group a template without capturing, for example. (?:http|https) matches http or https but doesn't commit it.

+4
source

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

or use preg_replace to get what you need from $content .

+1
source

Source: https://habr.com/ru/post/1339666/


All Articles