简体   繁体   中英

php Regular Expression return specific string

Let us say, I want to return a name:

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

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

print_r($matches);

The result is:

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

Well, let's see this:

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

With this I get: Array

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

which is more or less the same string I passed.

What I am looking for is to compare and extract the variables so that I could use them as variable $1 and $2 or anything like this works.

Or maybe a method that returns an associate array or those items like:

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

Any workaround or ideas are highly appreciated as long as they work in the way I asked above.

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

returns

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

\\\\S matches non-whitespace.

Change it to . to match anything, which will work as far as the other strings in the pattern ("My name is " and " I like ") are fixed.

Not so clean but might be helpful...

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

}

It returns:

Array
(
    [0] => John Cena
    [1] => Ice-cream
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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