2016-11-23 269 views
0

我有一個字符串,看起來像這樣"<html>"。現在我想要做的是獲取"<"">"之間的所有文本,並且這應該適用於任何文本,所以如果我做了"<hello>""<p>"那也可以。然後我想用包含標籤之間的字符串的字符串替換此字符串。 例如
在:PhP查找(並替換)兩個不同字符串之間的字符串

<[STRING]> 

輸出:

<this is [STRING]> 

在哪裏[字符串]是標記之間的字符串。

+0

http://php.net/manual/en/function.strip-tags.php – Farkie

+1

我說你應該看看正則表達式,但你已經標記了他們。所以相反,我會問:你有什麼*嘗試*迄今? –

+2

[你是否用正則表達式解析html?](http://stackoverflow.com/a/1732454/1641867) - 不要認爲這是一個好主意。 – ventiseis

回答

1

使用捕獲組來匹配<之後不是>的所有內容,並將其替換爲替換字符串。

preg_replace('/<([^>]*)>/, '<this is $1>/, $string); 
0

我不知道這對你是否有用。 您可以使用正則表達式最佳方式。但是你也可以考慮一個小函數,從你的字符串中首先刪除<和最後的> char。

這是我的解決方案:

<?php 

/*Vars to test*/ 

$var1="<HTML>"; 
$var2="<P>"; 
$var3="<ALL YOU WANT>"; 

/*function*/ 

function replace($string_tag) { 
$newString=""; 
for ($i=1; $i<(strlen($string_tag)-1); $i++){ 
    $newString.=$string_tag[$i]; 
} 

return $newString; 

} 

/*Output*/ 

echo (replace($var1)); 
echo "<br>"; 
echo (replace($var2)); 
echo "<br>"; 
echo (replace($var3)); 

?> 

輸出給我:
HTML
P
所有你想要的

測試在http://phptester.net/

1

這裏是測試上的圖案的解決方案存在然後捕獲它以最終修改它...

<?php 
$str = '<[STRING]>'; 
$pattern = '#<(\[.*\])>#'; 

if(preg_match($pattern, $str, $matches)): 
    var_dump($matches); 
    $str = preg_replace($pattern, '<this is '.$matches[1].'>', $str); 
endif; 

echo $str; 
?> 

echo $ str; 您可以測試在這裏:http://ideone.com/uVqV0u

相關問題