【发布时间】:2011-08-08 00:12:23
【问题描述】:
我想得到两个字符串之间的字符串。
background:url(images/cont-bottom.png) no-repeat;
基本上我想获取url( 和) 之间的所有文本
希望有人可以帮助我。谢谢!
【问题讨论】:
-
您应该先尝试自己并在此处发布您的代码。然后,我们会尽力提供帮助。
标签: php preg-match preg-match-all
我想得到两个字符串之间的字符串。
background:url(images/cont-bottom.png) no-repeat;
基本上我想获取url( 和) 之间的所有文本
希望有人可以帮助我。谢谢!
【问题讨论】:
标签: php preg-match preg-match-all
preg_match('~[(](.+?)[)]~',$string,$matches);
【讨论】:
<?
$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
*/
?>
【讨论】:
(.*?) 不会继续换行搜索匹配项,但(.*) 会继续换行
$string = 'background:url(images/cont-bottom.png) no-repeat;';
preg_match_all("#background:url\((.*?)\)#", $string, $match);
echo $match[1][0];
输出:
images/cont-bottom.png
【讨论】:
试试这个正则表达式:
/url\s*\([^\)]+\)/
【讨论】:
针对这种特殊情况试试这个
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);
【讨论】: