Bryan
Bryan

Reputation: 19

preg_match_all get text between 2 strings

I would like 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!

Upvotes: 0

Views: 8747

Answers (5)

Fthr
Fthr

Reputation: 807

(.*?) 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

Upvotes: 1

Ravi Verma
Ravi Verma

Reputation: 225

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

Upvotes: -2

Pedro Lobito
Pedro Lobito

Reputation: 98881

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

Upvotes: 2

The Mask
The Mask

Reputation: 17427

Try this regex:

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

Upvotes: 0

RiaD
RiaD

Reputation: 47619

preg_match('~[(](.+?)[)]~',$string,$matches);

Upvotes: 2

Related Questions