2017-06-20 56 views
0

如何應用這個正則表達式?在Php 我有代碼如何應用此正則表達式?在php

$a = "{temp}name_temp1{/temp} Any thing Any thing {temp}name_temp2{/temp}"; 

我只需要name_temp1name_temp2

任何名稱裏面{溫度} {/ TEMP}

感謝您

+0

使用preg_match_all,所以它在第一次出現後不會停止,'{tempb [^>] *}(。*?){/ temp}' – clearshot66

+1

[RegEx匹配文本在分隔符之間匹配](https:// stackoverflow .com/questions/3697644/regex-match-text-in-between-delimiters) – revo

回答

3

你可以使用一個懶惰的量詞:

{temp}   # look for {temp} 
(?P<value>.+?) # anything else afterwards 
{/temp}  # look for {/temp} 


PHP這將是:

<?php 

$a = "{temp}name_temp1{/temp} Any thing Any thing {temp}name_temp2{/temp}"; 

$regex = '~{temp}(?P<value>.+?){/temp}~'; 
preg_match_all($regex, $a, $matches, PREG_SET_ORDER); 

foreach($matches as $match) { 
    echo $match["value"]; 
} 
?> 
+1

這裏'\ Q ... \ E'序列的用途是什麼? – revo

+0

爲什麼一個花括號不表示特殊含義!? – revo

+0

你做到了,但也需要修改初始描述。 – revo

2

試試這個正則表達式:{temp}(.*?){\/temp}

而且你可以使用它在PHP這樣的:

$a = "{temp}name_temp1{/temp} Any thing Any thing {temp}name_temp2{/temp}"; 

preg_match_all('/{temp}(.*?){\/temp}/', $a, $matches); 

var_dump($matches[1]); // Returns ['name_temp1', 'name_temp2'] 

eval.in demo

+0

感謝您的回覆 – ibrahimqd