簡體   English   中英

PHP正則表達式返回特定的字符串

[英]php Regular Expression return specific string

讓我們說,我想返回一個名稱:

$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")

只要能夠按照我上面的要求進行操作,任何變通方法或想法都將受到高度贊賞。

$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匹配非空格。

將其更改為. 匹配任何東西,只要模式中的其他字符串(“我的名字是”和“我喜歡”)是固定的,都可以使用。

不太干凈但是可能會有所幫助...

$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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM