Get Everything between two characters
I'm using PHP. I'm trying to get a Regex pattern to match everything between value=开发者_StackOverflow" and " i.e. Line 1 Line 2,...,to Line 4.
value="Line 1
Line 2
Line 3
Line 4"
I've tried /.*?/
but it doesn't seem to work.
I'd appreciate some help.
Thanks.
P.S. I'd just like to add, in response to some comments, that all strings between the first " and last " are acceptable. I'm just trying to find a way to get everything between the very first " and very last " even when there is a " in between. I hope this makes sense. Thanks.
Assuming the desired character is "double quote":
$pat = '/\"([^\"]*?)\"/'; // text between quotes excluding quotes
$value='"Line 1 Line 2 Line 3 Line 4"';
preg_match($pat, $value, $matches);
echo $matches[1]; // $matches[0] is string with the outer quotes
if you just want answer and not want specific regex,then you can use this:
<?php
$str='value="Line 1
Line 2
Line 3
Line 4"';
$need=explode("\"",$str);
var_dump($need[1]);
?>
/.*?/
has the effect to not match the new line characters. If you want to match them too, you need to use a regular expression like /([^"]*)/
.
I agree with Josh K that a regular expression is not required in this case (especially if you know there will not be any apices apart the one to delimit the string). You could adopt the solution given by him as well.
If you must use regex:
if (preg_match('!"([^"]+)"!', $value, $m))
echo $m[1];
You need s
pattern modifier. Something like: /value="(.*)"/s
I'm not a regex
guru, but why not just explode it?
// Say $var contains this value="..." string
$arr = explode('value="');
$mid = explode('"', $arr[1]);
$fin = $mid[0]; // Contains what you're looking for.
The specification isn't clear, but you can try something like this:
/value="[^"]*"/
Explanation:
- First,
value="
is matched literally - Then, match
[^"]*
, i.e. anything but"
, possibly spanning multiple lines - Lastly, match
"
literally
This does not allow "
to appear between the "real" quotes, not even if it's escaped by e.g. preceding with a backslash.
The […]
is a character class. Something like [aeiou]
matches one of any of the lowercase vowels. [^…]
is a negated character class. [^aeiou]
matches one of anything but the lowercase vowels.
References
- regular-expressions.info/Examples - Programming Language Constructs - Strings
- Has variations on different string patterns (e.g. allowing escaped quotes)
Related questions
- Difference between
.*?
and.*
for regex- As much as is practical, negated character class is always a better option than
.*?
- As much as is practical, negated character class is always a better option than
精彩评论