开发者

preg_match_all get text between 2 strings

开发者 https://www.devze.com 2023-03-26 07:27 出处:网络
I would like开发者_如何学JAVA to get string between 2 strings. background:url(images/cont-bottom.png) no-repeat;

I would like开发者_如何学JAVA to get string between 2 strings.

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

Basically I would like to get all text between url( and )

Hope somebody can help me. thanks!


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
*/    
?>


(.*?) will not continue to a new line to search matches, but (.*) will continue to a new line

$string = 'background:url(images/cont-bottom.png) no-repeat;';

preg_match_all("#background:url\((.*?)\)#", $string, $match);

echo  $match[1][0];

Output:

images/cont-bottom.png


Try this regex:

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


try this for this particular situation

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);
0

精彩评论

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