簡體   English   中英

preg_match_all獲取2個字符串之間的文本

[英]preg_match_all get text between 2 strings

我想在2個字符串之間獲取字符串。

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

基本上我想在url()之間獲取所有文本

希望有人可以幫助我。 謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM