[英]regex expression match parts of an string
I am trying to match parts of an string into variables after getting the page from curl 我从卷曲获取页面后试图将字符串的一部分匹配为变量
the string is 字符串是
value="http://ca.isohunt.com/upload.php?mode=bt&id=880001&sid=3096d80a1c9d2962f8f35a837a3f23e0"
I am trying to get &id=''
and $sid=''
我正在尝试&id=''
和$sid=''
i tried using this regex expression using preg_match and it did not work 我尝试使用preg_match使用此regex表达式,但它不起作用
/([^_]*?)&sid-.*?\$
You shouldn't use regular expressions for this. 您不应该为此使用正则表达式。
If your input string includes value="
(and the "
at the end) just extract the URL. 如果您的输入字符串包括value="
(与"
末)只是提取URL。 You could probably do this easiest using substr
: 您可以使用substr
最简单地执行此操作:
$url = substr($input, 7, -1);
If the string is more variable, and all you know is that the URL is the stuff inside the quotes, use: 如果字符串的可变性更大,并且您所知道的只是URL是引号内的内容,请使用:
preg_match('/".*"/', $input, $match);
$url = $match[0];
If your $input
has only the URL, you can of course skip this step completely. 如果$input
仅具有URL,那么您当然可以完全跳过此步骤。 Then: 然后:
$query = parse_url($url, PHP_URL_QUERY);
$params = array();
parse_str($query, $params);
echo $params['mode']; // bt
echo $params['id']; // 880001
echo $params['sid']; // 3096d80a1c9d2962f8f35a837a3f23e0
Use parse_url
使用parse_url
$url = 'http://username:password@hostname/path?arg=value#anchor';
$data = parse_url($url);
print_r(parse_url($url));
The above example will output: 上面的示例将输出:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
Then: 然后:
$queryFields = split('[&]', $data['query']);
First off, you shouldn't escape the $
unless you're expecting it in the "value" string. 首先,除非您期望在“ value”字符串中使用$
否则不要转义$
。
Your regex could be /&?sid=([^&]+)/
and /&?id=([^&]+)/
, provided that you don't want to do any checking on the url itself. 您的正则表达式可以是/&?sid=([^&]+)/
和/&?id=([^&]+)/
,前提是您不想对URL本身进行任何检查。 Or combined: /&?id=([^&]+).*&?sid=([^&]+)/
. 或组合:/&? /&?id=([^&]+).*&?sid=([^&]+)/
.*&? /&?id=([^&]+).*&?sid=([^&]+)/
。
Remember that the values will be exported to $matches[1]
and $matches[2]
when you're calling something like preg_match('/&?id=([^&]+).*&?sid=([^&]+)/', $value, $matches);
请记住,当您调用诸如preg_match('/&?id=([^&]+).*&?sid=([^&]+)/', $value, $matches);
$matches[2]
时,这些值将导出为$matches[1]
和$matches[2]
preg_match('/&?id=([^&]+).*&?sid=([^&]+)/', $value, $matches);
if ($c=preg_match_all ("/.*?(id=)(\d+).*?(sid=)([a-zA-Z0-9_]{1,})/is", $txt, $matches))
{
$id=$matches[2][0];
$sid=$matches[4][0];
print "id = $id <br> sid = $sid\n";
}
Here is the code that you can use to get the 2 values. 这是可用于获取2个值的代码。 This gets you the values of the 2 parameters. 这将为您提供2个参数的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.