【问题标题】:PHP Preg match - get wrapped valuePHP Preg 匹配 - 获取包装值
【发布时间】:2015-12-23 08:59:31
【问题描述】:

我想使用 preg match 提取所有包装的文本值

所以

background: url("images/gone.png");
color: #333;
...

background: url("images/good.png");
font-weight: bold;

从上面的字符串, 我要抢

images/gone.png
images/good.png

什么是正确的命令行?

【问题讨论】:

标签: php regex preg-match


【解决方案1】:

在 php 中,你应该这样:

$str = <<<CSS
    background: url("images/gone.png");
    color: #333;

    background: url("images/good.png");
    font-weight: bold;
CSS;

preg_match_all('/url\("(.*?)"\)/', $str, $matches);
var_dump($matches);

然后,你会看到类似这样的输出:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(22) "url("images/gone.png")"
    [1]=>
    string(22) "url("images/good.png")"
  }
  [1]=>
  array(2) {
    [0]=>
    string(15) "images/gone.png"
    [1]=>
    string(15) "images/good.png"
  }
}

因此,带有 url 的列表将在 $matches[1] :)

【讨论】:

    【解决方案2】:

    http://www.phpliveregex.com/p/e3u

    这个正则表达式会这样做:

    /^background: url\("(.*?)"\);$/
    

    最好学习一些关于正则表达式的知识,值得花时间: http://regexone.com/

    【讨论】:

      【解决方案3】:
      $regex = '~background:\s*url\([\"\']?(.*?)[\"\']?\);~i';
      $mystr = 'background: url("images/gone.png");
      color: #333;
      ...
      
      background: url("images/good.png");
      font-weight: bold;';
      preg_match_all($regex, $mystr, $result);
      print_r($result);
      
      ***Output:***
      Array ( [0] => Array ( [0] => background: url("images/gone.png"); [1] => background: url("images/good.png"); ) [1] => Array ( [0] => images/gone.png [1] => images/good.png ) )
      

      【讨论】:

        【解决方案4】:
        $pattern = '/(?:\"([^\"]*)\")|(?:\'([^\']*)\')|(?:\(([^\(]*)\))/i';
        $string = '
        background: url("images/gone.png1");
        background: url(\'images/gone.png2\');
        background: url(images/gone.png3);
        color: "#333;"';
        preg_match_all($pattern, $string,$matches);
        print_r($matches[0]);
        

        正则表达式将获取所有出现在双引号中的字符串。

        如果您只想获取背景,我们可以在正则表达式模式中添加相同的字符串。

        【讨论】:

        • 有几个 CSS 属性可以用引号括起来(例如属性content)。顺便说一句,url("images/gone.png") 也可以用单引号或不带引号书写。
        • 如果我理解正确封闭的意思 - 1. 在单引号内。 2. 双引号内。 3. 括号内。如果我误解了,请纠正我。
        • 图像路径周围总是有括号,只有引号是可选的。但正如我在 cmets 中所说,最好使用解析器,因为 CSS 文件中有太多陷阱。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 2018-02-22
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多