Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preg_replace regex to replace this HTML tag?

How would I convert strings like this:

<span class="it">CONTENT</span>

Into this:

{it}CONTENT{/it}

While keeping CONTENT intact?

like image 626
Dannyboy Avatar asked Jan 07 '14 17:01

Dannyboy


People also ask

What does preg_ replace() return?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.

What is the difference between Preg_replace and Str_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

How to remove HTML tags from string in PHP?

PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.


1 Answers

preg_replace('/<span class="it">(.*?)<\/span>/', '{it}$1{/it}', $text)

This is not the most versatile solution, but this works for your code. There is the possibility to have the content of the class attribute as a variable as well, but that won't be too hard to figure out now.

like image 158
Mave Avatar answered Oct 10 '22 21:10

Mave