【问题标题】:preg_match_all get text between 2 stringspreg_match_all 获取两个字符串之间的文本
【发布时间】:2011-08-08 00:12:23
【问题描述】:

我想得到两个字符串之间的字符串。

background:url(images/cont-bottom.png) no-repeat;

基本上我想获取url() 之间的所有文本

希望有人可以帮助我。谢谢!

【问题讨论】:

  • 您应该先尝试自己并在此处发布您的代码。然后,我们会尽力提供帮助。

标签: php preg-match preg-match-all


【解决方案1】:
preg_match('~[(](.+?)[)]~',$string,$matches);

【讨论】:

  • 包括括号。
【解决方案2】:
<?
$css_file = 
   'background:url(images/cont-bottom.png) no-repeat;
    background:url(images/cont-left.png) no-repeat;
    background:url(images/cont-top.png) no-repeat;
    background:url(images/cont-right.png) no-repeat;';

//matches all images inside the css file and loop the results

preg_match_all('/url\((.*?)\)/i', $css_file, $css_images, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($css_images[0]); $i++) {
   echo $css_images[1][$i]."<br>";
}

/*
Outputs:
images/cont-bottom.png
images/cont-left.png
images/cont-top.png
images/cont-right.png
*/    
?>

【讨论】:

    【解决方案3】:

    (.*?) 不会继续换行搜索匹配项,但(.*) 会继续换行

    $string = 'background:url(images/cont-bottom.png) no-repeat;';
    
    preg_match_all("#background:url\((.*?)\)#", $string, $match);
    
    echo  $match[1][0];
    

    输出:

    images/cont-bottom.png
    

    【讨论】:

      【解决方案4】:

      试试这个正则表达式:

      /url\s*\([^\)]+\)/
      

      【讨论】:

        【解决方案5】:

        针对这种特殊情况试试这个

        function getInbetweenStrings($start, $end, $str){
            $matches = array();
            $regex = "/$start(.*)$end/";
            preg_match_all($regex, $str, $matches);
            return $matches[1];
        }
        
        $str = "background:url(images/cont-bottom.png) no-repeat;";
        $str_arr = getInbetweenStrings("\(", "\)", $str);
        
        echo '<pre>';
        print_r($str_arr);
        

        【讨论】:

        • 它返回空字符串,因此如果您使用例如,这不是一个好的解决方案。 {START} {STOP} 字符串作为某种标签。
        猜你喜欢
        • 1970-01-01
        • 2019-10-10
        • 2013-04-02
        • 2014-10-03
        • 2012-12-28
        • 1970-01-01
        • 2023-02-13
        • 2018-05-03
        相关资源
        最近更新 更多