ObiHill
ObiHill

Reputation: 11876

Get Everything between two characters

I'm using PHP. I'm trying to get a Regex pattern to match everything between value=" 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.

Upvotes: 2

Views: 8135

Answers (7)

polygenelubricants
polygenelubricants

Reputation: 383726

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

Related questions

Upvotes: 0

racetrack
racetrack

Reputation: 3756

You need s pattern modifier. Something like: /value="(.*)"/s

Upvotes: 1

Sergei
Sergei

Reputation: 2757

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

Upvotes: 4

NullUserException
NullUserException

Reputation: 85458

If you must use regex:

if (preg_match('!"([^"]+)"!', $value, $m))
    echo $m[1];

Upvotes: 1

avpaderno
avpaderno

Reputation: 29669

/.*?/ 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.

Upvotes: 1

Ankur Mukherjee
Ankur Mukherjee

Reputation: 3867

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]);
?>

Upvotes: 1

Josh K
Josh K

Reputation: 28883

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.

Upvotes: 0

Related Questions