簡體   English   中英

匹配字符串中的單個字符,然后在 PHP 中使用 Regex 替換該字符

[英]Match a single character within a string and then replace that character using Regex in PHP

我有這個代碼:

 <p><br>< br> </ strong> </ div>

所以我需要的是匹配和替換“</”和“[a-zA-Z]+>”之間的“\\s”或“”(空),所以基本上使用“/</( [ ]+)[az]+>/g" 但它匹配所有鏈,我只需要匹配單個字符並替換它。

順便說一句,現在我正在使用下面的代碼來替換空我的意思是刪除空字符。 但我想知道我問的是否可能。 謝謝。

//this code replace what I need    
$htmlfixed = preg_replace('/(?<=<\/)([ ]+)(?=[a-zA-Z]+>)/', '', $html);

這可能是實現這一目標的一種方式,

 const regex = /(<\\/?)[\\s]/gm; const str = `<p><br>< br> </ strong> </ div>`; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result);

見正則表達式

您現有的代碼也將刪除該標簽。 您只需要刪除</和標記之間的空格,因此您可以使用正則表達式(?<=</)\\s+即空格 ( \\s+ ) 前面是</

$html = '<p><br>< br> </ strong> </ div>';
$htmlfixed = preg_replace('#(?<=</)\s+#', '', $html);
echo $htmlfixed;

輸出:

<p><br>< br> </strong> </div>

3v4l.org 上的演示

暫無
暫無

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

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