[英]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.