Nytrix
Nytrix

Reputation: 1139

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.

Upvotes: 0

Views: 274

Answers (2)

panepeter
panepeter

Reputation: 4242

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!

Upvotes: 2

Vinoth Sd
Vinoth Sd

Reputation: 112

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

Upvotes: -1

Related Questions