简体   繁体   English

删除字符串中某些字符的第一个

[英]Remove first of certain character in string

For instance I have html between < > these tags. 比如我有html之间< >这些标记。 I want to keep the html alive. 我想让html保持活力。 Firstly I just did a replace. 首先,我只是做了一个替换。

str_replace(array("<",">"),"",$string);

This of course removed all the < and > from the html. 当然,这会从html中删除所有<> Is there a way to get the first < character? 有没有办法获得第一个<字符? And replace that? 并替换它? This would make it more friendly for usage. 这将使其使用更加友好。 Or is substr($str, 0, 1) the only option here? 还是substr($str, 0, 1)是这里唯一的选择?

Example

$str = " here can be letters too <some html code <h1> a header </h1> >";

Output 输出量

some html code <h1> a header </h1>

There is not always a space after the < tag. <标记后并不总是有space

To remove the first of a certain character in a String (like your question suggests), use preg_replace with the limit argument. 要删除字符串中某个字符的第一个字符(如您的问题所示),请使用带有limit参数的preg_replace This would remove only the first occurence of "<": 这将仅删除“ <”的第一次出现:

$newstring = preg_replace("/</", "", $oldstring, 1);

To remove everything up until a given character (as your edit suggests), use this: 要删除直到给定字符为止的所有内容(如您的编辑建议),请使用以下命令:

$newstring = preg_replace("/[^<]*<(.*)/", "$1", $oldstring);

This would remove everything before (and including) the "<". 这将删除“ <”之前(包括“ <”之前的所有内容)。

Please learn about Regular Expressions! 了解正则表达式!

You can you htmlentities to convert the html tags like below 您可以htmlentities转换html标签,如下所示

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM