[英]Reposition value of string after replace html tag - PHP
ex1: This <b>is bold</b> and this <i>is italic</i> this is <i>also italic</i>
ex2: This is <b><i>bold-italic</i></b> But this <b>is bold</b> this is <b>also bold</b>
現在我可以通過遞歸strpos
function 獲得標簽之間的字符串 position。
但我將刪除 html 標簽,並希望獲得這些字符串的 position 值。
像:
5 和 15 的 position 中的第一個bold
字符串。但是當我刪除標簽時,它不會保留在相同的 position 上。
你能給我一些想法嗎,如何在 strip 標簽后重新定位字符串?
這是在該論壇中找到的遞歸 strpos:
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
$offset = strpos($haystack, $needle, $offset);
if($offset === false) {
return $results;
} else {
$results[] = $offset;
return strpos_recursive($haystack, $needle, ($offset + 1), $results);
}
}
所以,我可以通過使用這個 function 得到 position 的字符串。但是如何在刪除標簽后重新定位?
首先,建議使用合適的 HTML 解析函數/庫來處理這個問題。 但是,如果您確實需要正則表達式,則可以使用以下查詢來匹配標簽及其內部文本:
<(\w+)>(.*?)<\/\1>
您可以將其替換為標記為\2
的內部組。 所以它看起來像這樣:
preg_replace("<(\w+)>(.*?)<\/\\1>", "\\2", str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.