简体   繁体   English

如何从PHP中的preg_match获取特定值

[英]How to get particular value from preg_match in php

I need this value from given URL. 我需要来自给定URL的值。 I write a function in PHP, but could not get proper value. 我用PHP编写了一个函数,但无法获得正确的值。

URL: 网址:

<a href="/search/name?birth_place=Madras,%20Tamil%20Nadu,%20India&amp;ref_=nmbio_ov_3">Madras, Tamil Nadu, India</a>

Function: 功能:

function match($regex, $str, $i = 0){
    if(preg_match($regex, $str, $match) == 1)
        return $match[$i];
    else
        return false;
}

$arr = array();<br>
$arr['birthplace'] = trim(match('/&lt;a href="\/search\/name\?birth_place=.+?">(.*?)<\/a>/', '&lt;a href="/search/name?birth_place=Madras,%20Tamil%20Nadu,%20India&amp;ref_=nmbio_ov_3">Madras, Tamil Nadu, India&lt;/a>', 1));

Also, I want to get 2 values like whatever matches in () should be stored in array. 另外,我想获得2个值,例如()中的任何匹配项都应存储在数组中。 For example in above expression if I make () 2 times then the function should capture both of the cases. 例如,在上面的表达式中,如果我执行()2次,则该函数应捕获这两种情况。

You may try this approach ( run here ) 您可以尝试这种方法( 在此处运行

$re = '/birth_place=\K[^&]+/';
$str = '<a href="/search/name?birth_place=Madras,%20Tamil%20Nadu,%20India&ref_=nmbio_ov_3">Madras, Tamil Nadu, India<\\/a>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
$arr=explode(',%20',$matches[0][0]);
foreach($arr as $key=>$value) 
$arr[$key] = preg_replace('/%20/','',$arr[$key]);
print_r($arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM