简体   繁体   English

PHP /正则表达式获取一组双引号之间的内容

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

Update to my question: My goal overall is to split the string into 4 parts that I can access later. 更新至我的问题:我的总体目标是将字符串分成4部分,以后可以访问。

  1. value
  2. = =
  3. "
  4. result of the html inside the first and last " " 第一个和最后一个“”内的html的结果

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 first 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. 基本上,链接上的双引号引起了我的麻烦,所以我的第一个操作是执行[^“] $或使它一直运行到最后一个双引号,但这并没有使我到处走。可能是在PHP中处理字符串以去除任何内部引号,但是我不确定该如何去做。

Hopefully I'm being clear, it is pretty late and i've been at this far too long! 希望我很清楚,已经很晚了,而且我已经走了太久了!

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 真诚的

如果您不花一点时间更改html,可以尝试以下操作:

$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>

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). 您无法执行此操作,因为您不知道哪个引号标记要匹配的字符串的末尾以及应该包括哪个引号(尤其是当值中的引号数量可变且字符串中的匹配项超过1个时)。 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. 对我来说似乎很奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM