php Regular Expression返回特定的字符串

时间:2015-11-11 10:09:42

标签: php regex

让我们说,我想要一个名字:

$re = "/(name is )[a-z- ]*( )/i";
$str = "My name is John ";

preg_match($re, $str, $matches);

print_r($matches);

结果是:

Array
(
    [0] => name is John 
    [1] => name is 
    [2] =>  
)

好吧,让我们看看:

$string = "My name is John and I like Ice-cream";
$pattern = "My name is $1 and I like $2";

有了这个我得到: 阵列

(
    [0] => name is John and I like Ice-cream 
    [1] => name is 
    [2] =>  and I like 
    [3] =>  
)

这或多或少与我传递的字符串相同。

我正在寻找的是比较和提取变量,以便我可以将它们用作变量$1$2或类似的任何工作。

可能返回关联数组或类似项目的方法:

Array("1" => "John" , "2" => "Ice-cream")

任何解决方法或想法都会受到高度赞赏,只要它们按照我上面提到的方式工作。

2 个答案:

答案 0 :(得分:3)

$str = 'My name is John and I like Ice-cream';
$re = '/My name is (\S+) and I like (\S+)/';
preg_match($re, $str, $matches);

print_r($matches);

返回

Array
(
    [0] => My name is John and I like Ice-cream
    [1] => John
    [2] => Ice-cream
)

\\S匹配非空格。

将其更改为.以匹配任何内容,这将与模式中的其他字符串一样有效("我的名字是""我喜欢" )是固定的。

答案 1 :(得分:1)

不太干净但可能会有所帮助...

$string = "My name is John Cena and I like Ice-cream";
$pattern = "My name is $ and I like $";
print_r(getArray($string, $pattern));

function getArray($input, $pattern){

    $delimiter = rand();
    while (strpos($input,$delimiter) !== false) {
        $delimiter++;
    }

    $exps = explode("$",$pattern);
    foreach($exps as $exp){
        $input = str_replace($exp,",", $input);
    }

    $responses = explode(",", $input);
    array_shift($responses);
    return $responses;

}

它返回:

Array
(
    [0] => John Cena
    [1] => Ice-cream
)
相关问题