开发者

Php/Regex get the contents between a set of double quotes

开发者 https://www.devze.com 2023-03-29 20:03 出处:网络
Update to my question: My goal overall is to split the string into 4 parts that I can access later. value

Update to my question: My goal overall is to split the string into 4 parts that I can access later.

  1. value
  2. =
  3. "
  4. result of the html inside the first and last " "

Here is an example of what i'm trying to do:

// My string (this is dynamic and will change, this is just an example)

$string = 'value="<p>Some text</p> <a href="#">linky</a>"';

// Run the match and spit out the results

preg_match_all('/([^"]*)(?:\s*=\s*(\042|\047))([^"]*)/is', $string , $results);

// Here is the array I want to end up with

Array
(
[0] => Array
    (
        [0] => value="<p>Some text</p><a href="#">linky</a>"
    )

[1] => Array
    (
        [0] => value
    )

[2] => Array
    (
        [0] => "
    )

[3] => Array
    (
        [0] => <p>Some text</p><a href="#">linky</a>
    )
)

Basically the double quotes on the link are causing me some trouble so my fir开发者_StackOverflow社区st though was to do [^"]$ or something to have it just run until the last double quote, but that isn't getting me anywhere. Another idea I had was maybe process the string in PHP to strip out any inner quotes, but i'm not sure ho to go about this either.

Hopefully I'm being clear, it is pretty late and i've been at this far too long!


You cannot do this, because you don't know how which quote marks the end of the string to match and which should be included (especially when there's a variable number of quotes in the values, and more than 1 match in the string). How come are there quotes within quotes anyway? Where does this data come from?

$string = 'value="<p>Some text</p> <a href="#">linky</a>"';

Just seems very strange to me.


If you don't bother changing your html a little bit, you can try this:

$string = 'value="<p>Some text</p> <a href=\'#\'>linky</a>"';


In this case, you can use:

$string = 'value="<p>Some text</p> <a href="#">linky</a>"';
echo substr( $string, 7, -1 ); //<p>Some texts</p> <a href="#">linky</a>


Try this regex

$string = 'value="<p>Some text</p> <a href="#">linky</a>"';
$regex = '/([^"]*)(?:\s*=\s*(?:\042|\047))(.*)(?:\042|\047)(?:[^"]*)/is';
preg_match_all($regex, $string , $results);

it gives following result.

Array(3) {
  [0]=>
  Array(1) {
    [0]=>
    string(46) "value="<p>Some text</p> <a href="#">linky</a>""
  }
  [1]=>
  Array(1) {
    [0]=>
    string(5) "value"
  }
  [2]=>
  Array(1) {
    [0]=>
    string(38) "<p>Some text</p> <a href="#">linky</a>"
  }
}

Sincerely

0

精彩评论

暂无评论...
验证码 换一张
取 消