Reputation: 67
I would like to ask about php's preg_match_all. suppose we have the sample string below:
This is a clause with -value1- and -_value_2_- having a subclause of -value.3- items.
And i would like to extract all strings with the opening "-" and closing "-" characters. Needed output should be:
Array
(
[0] => Array
(
[0] => -_value1_-
[1] => -_value_2_-
[2] => -_value.3_-
)
)
Upvotes: 1
Views: 343
Reputation: 2973
You could use T-Regx library that automatically adds delimiters
pattern('-.*?-')->match($string)->all();
the result is
Array
(
[0] => -_value1_-
[1] => -_value_2_-
[2] => -_value.3_-
)
Upvotes: 0
Reputation: 5462
Sometimes preg_match_all()
can be too complicated. In these cases you can use explode
for this aim.
$matches = explode("-", $input);
What explode()
does?
$input = "This is a basic example: -JOHN-. The End";
explode()
converts $matches
to an array. After that searches $input
for "-" character. After finding the "-" it will set array like below.
$input[0]
---> "This is a basic example: "
$input[1]
---> "JOHN"
$input[2]
---> ". The End"
explode()
is an alternative way. But the best one is of course preg_match_all()
Upvotes: 0
Reputation: 784998
You can use this code:
$str="This is a clause with -value1- and -_value_2_- having a subclause of -value.3- items.";
if (preg_match_all('/-[^-]*-/', $str, $m))
print_r($m[0]);
Upvotes: 0
Reputation: 16214
Use one of the following simple regexps /-.*?-/
or /-.*-/U
U (PCRE_UNGREEDY) This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).
Upvotes: 2