PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to perform regex tag conversions to all occurrences in a string in PHP?

 November 20, 2022     html, php, preg-replace, regex, replace     No comments   

Issue

I want to convert my html strings which contain <p style=“text-align:center; others-style:value;”>Content</p> to <center>Content</center>, and <p style=“text-align:right; others-style:value;”>Content</p> to <right>Content</right> etc.

My previous question has an answer which can achieve this perfectly. Which is regex is:

$RegEx = '/<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s';
$string = preg_replace($RegEx, '<$4>$7</$4>', $string);

However, my strings may contain more than one occurrences of the text-align. For example, I might have <div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p> I want it to become <left>Any Content That You Wish</left><center>Content</center>, but it would just output <center>Content</center>.

How can I get what I want in PHP? Many thanks.


Solution

As I wrote in the comments, you should not use regex for manipulating html content. But only if you have non-nested tags in your html, you can go for it.

For this particular case, you can use this regex,

<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\1>

And replace it with <\2>\3</\2>

Regex Demo

PHP code demo

$html = '<p style=“text-align:center; others-style:value;”>Content</p>
<div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>';

$newhtml = preg_replace("~<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\\1>~", '<\2>\3</\2>', $html);
echo $newhtml;

Prints,

<center>Content</center>
<left>Any Content That You Wish</left><center>Content</center>


Answered By - Pushpesh Kumar Rajwanshi
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing