<?php
$str = 'window.location.href="http://my-site.com";';
preg_match('/window\.location\.href="(.*?)";/', $str, $result);
echo $result[1];
//http://my-site.com
>?
Extract url from string via preg match in php
-
07-07-2023 - |
题
$str = 'window.location.href="http://my-site.com";'
I want to extract the url from $str
. I am not that good in preg_match()
. However with the following code:
preg_match('/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/', $str, $link);
if (empty($link[0])) {
echo "Nothing found!";
} else {
echo $link[0];
}
I am able to get the result http://my-site.com";
. I want to customize preg_match() to exclude ";
from the result. Please help!
解决方案
其他提示
If you dont feel comfortable with preg_* then try keeping it simple. It seems a bit of an unnecessary overhead loading the regex engine anyway for something that simple.
Try this instead :-
$str = 'window.location.href="http://my-site.com";';
$p1 = strpos($str, 'href="') + strlen('href="');
$p2 = strpos($str, '";', $p1);
$url = substr($str,$p1,$p2-$p1);
echo $p1 .PHP_EOL;
echo $p2 .PHP_EOL;
echo $url;
This yeilds the following
22
40
http://my-site.com
i.e everything between href="
and ";
Try this:
preg_match('/^window.location.href="([^"]+)";$/', $str, $link);
不隶属于 StackOverflow