preg_match_all to find text between strings

Asked

Viewed 196 times

3

I’d like to pick up the text between "play_url":" and "," using PHP’s preg_match_all, only that these quotes are complicating me and I don’t even know what direction would be for the tracking code, what I currently have is this:

$texto: '"play_url":"http:/video.server.com/","'
preg_match_all('/"play_url"(.*?) ","/i', $texto, $link);

1 answer

1


The code is almost right, except for the space after the group and also the :" after the "play_url":

                          :"
                           ↓   ↓
preg_match_all('/"play_url"(.*) ","/i', $texto, $link);

The Lazy (?) also does not need in this case, since apparently there is no possibility of having another "," in string.

Would be:

<?
$texto = '"play_url":"http:/video.server.com/","';
preg_match_all('/"play_url":"(.*)","/i', $texto, $link);
var_dump($link[1]); // mostra array(1) { [0]=> string(23) "http:/video.server.com/" }
?>

To print the value:

echo $link[1][0]; // http:/video.server.com/

IDEONE

  • 2

    .*? also accepts "nothing" (empty string), that is, if the string is "play_url":"",, the URL will be empty. You can improve by placing for example [^"]+ (one or more occurrences of anything other than quotation marks), or something like [^"]{10,} (at least 10 characters other than quotation marks) which already guarantees that at least there has to be something between the quotation marks. If you want to go to the limit (or beyond), you can make bigger and more complex expressions, which check if it is a valid URL: https://stackoverflow.com/q/161738

  • 1

    It’s true. But I considered that the string will not come empty in this case, IE, always have something. Since the question does not indicate anything in the sense of the possibility of being empty, I restricted the answer to the scope of the question. But it is valid who wants to post a more complete answer, I do it very little, except in cases where it is explicit the possibility of the string to come empty. Or I could change the .*? for .+?. Because it’s very simple to ask, I don’t think I’d even need ?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.