简体   繁体   中英

Remove first of certain character in string

For instance I have html between < > these tags. I want to keep the html alive. Firstly I just did a replace.

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

This of course removed all the < and > from the 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?

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.

To remove the first of a certain character in a String (like your question suggests), use preg_replace with the limit argument. 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

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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