简体   繁体   中英

regex string between two characters from end php

Im trying to get a part of string doing regex. For eg.

$input = "This is a 'wonderful' day except i am 'stuck' here"

I want to get all characters between two ' s.

for this i'm using

preg_match('~\'(.*?)\'~', $input, $output);

but the result i'm getting is only wonderful in $output[0]

what i'm doing wrong? how to get the second part ie stuck in this example?

EDIT: I asked this question after checking $output[1]. ' stuck ' is not there!

also apart from testing it from my program, i also tried an online regex tester. here's the result:

http://s30.postimg.org/g6dj5xvmp/Selection_009.png

Do like this

<?php
$str = "This is a 'wonderful' day except i am 'stuck' here";
preg_match_all("/'(.*?)'/", $str, $matches);
print_r($matches[1]);

OUTPUT :

Array
(
    [0] => wonderful
    [1] => stuck
)

This is really quite simple. You're using preg_match , which attempts to find one occurance of a given pattern, to find all matches use preg_match_all .
Both work in the same way: the $matches array will have the full pattern-match assigned to index 0 (including the quotes), and the group(s) will be assigned to all subsequent indexes (in this case $matches[0] will contain the chars inside the quotes). The difference is that preg_match_all will assign arrays to the aforementioned indexes, listing each match for the pattern.

preg_match("/'([^]+)'/", $input, $matches);
var_dump($matches);

will give an array like this:

array(
    "'wonderful'",    //because the pattern mentions the ' chars
    "wonderful"       //because I'm grouping the chars inside the '
);

Whereas this code:

preg_match_all("/'([^']+)'/", $input, $matches));

Gives you:

array (
   //array of full matches, including the quotes
   array (
       '\'wonderful\'',
       '\'stuck\'',
   ),
   //array with groups
   array (
       'wonderful',
       'stuck',
   ),
);

As you can see on this live example

I've simplified your expression a little, because you're interested in what's "delimited" by single quotes, hence I match and group every non ' that follows a single quote and that is, in turn followed by another single quote. Thus, the char-class you want to match is simply [^'] ... anything except ' .
A possiple micro-optimization you could make to this suggested pattern would be to use a possessive quantifier ++ , which is similar to {1,} . Or, if you want to match an empty string if '' is found, you could use *+ . so

if (preg_match_all("/'([^']++)'/", $subject, $matches))
    var_dump($matches);

Should do the trick

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