[英]Remove first of certain character in string
比如我有html
之間< >
這些標記。 我想讓html
保持活力。 首先,我只是做了一個替換。
str_replace(array("<",">"),"",$string);
當然,這會從html中刪除所有<
和>
。 有沒有辦法獲得第一個<
字符? 並替換它? 這將使其使用更加友好。 還是substr($str, 0, 1)
是這里唯一的選擇?
例
$str = " here can be letters too <some html code <h1> a header </h1> >";
輸出量
some html code <h1> a header </h1>
<
標記后並不總是有space
。
要刪除字符串中某個字符的第一個字符(如您的問題所示),請使用帶有limit
參數的preg_replace 。 這將僅刪除“ <”的第一次出現:
$newstring = preg_replace("/</", "", $oldstring, 1);
要刪除直到給定字符為止的所有內容(如您的編輯建議),請使用以下命令:
$newstring = preg_replace("/[^<]*<(.*)/", "$1", $oldstring);
這將刪除“ <”之前(包括“ <”之前的所有內容)。
您可以htmlentities轉換html標簽,如下所示
<?php
$str = "A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.