2013-12-16 100 views
1

我想在HTML內容中進行字符串替換。使用字符串獲取值的正則表達式

<!-- REPLACE_STRING_5 --> 

爲了做到這一點,我需要得到的數出字符串(ID),我只是想檢查我是正確,高效地這樣做呢?

<?php 
$subject = "<!-- REPLACE_STRING_21 -->"; 
$pattern = '/^<!-- REPLACE_STRING_[0-9\.\-]+ -->/'; 

if(preg_match($pattern, $subject)) 
{ 
    $pos = strpos($subject, '-->'); 
    //20 is the number where the number postion start 
    $pos = $pos - 20; 
    echo substr($subject, 20, $pos); 
} 
else 
{ 
    echo 'not match'; 
} 
+0

當您完成後,您希望REPLACE_STRING_21看起來像什麼? – brandonscript

+0

我需要將'21'(21是ID)取出並查找數據庫,然後獲取內容並替換此'<! - REPLACE_STRING_21 - >' – Bruce

回答

2

如果你想真正取代你可以使用lookarounds爲此在REPLACE_STRING_21數量:

(?<=<!-- REPLACE_STRING_)[-0-9.]+(?= -->) 

enter image description here

工作例如:http://regex101.com/r/tK5cI1

由於你想要捕捉數字,你可以使用括號()部署捕捉組,就像這樣:

<!-- REPLACE_STRING_([-0-9.]+) --> 

工作例如:http://regex101.com/r/tV4tI3

然後,您需要檢索捕獲組1,像這樣:

$subject = "<!-- REPLACE_STRING_21 -->";  
preg_match("/<!-- REPLACE_STRING_([-0-9.]+) -->/", $subject, $matches); 
print_r($matches); 
if (isset($matches[1])) 
    echo $matches[1]; 

$matches將包含匹配的數組,在這種情況下,$matches[1]是你正在尋找的。

+0

這種環視對我來說是新的感謝。有用。投票。 – Bruce

+0

感謝您的幫助r3mus,您的解決方案是更好的方法,然後我的。非常熟悉 – Bruce

+0

不客氣!仍然爲了歷史的緣故,爲榜樣工作;) – brandonscript