0

I need to replace spaces inside a tag to other symbol. For example:

<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>

to

<p~class="hero~big"~style="color:~inherit;~border:~none">Super big hero <br~/>example Yeah</p>

I'm new to regexp and don't know to start with. I'm able to replace spaces everywhere, but not inside a tag.

Ho to do it? Could you please provide working php code?

Somerussian
  • 381
  • 4
  • 17
  • Possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Adnan Abdollah Zaki May 23 '16 at 10:26
  • 1
    What is your objective, why you want to remove space of tag properties – vishal May 23 '16 at 10:26

4 Answers4

0

try this, It will replace spaces inside tag with ~

<?php
  $data = '<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>';
  $replace = preg_replace('/(<[^>]*)\s+([^<]*>)/', '$1~$2', $data);
  echo $replace;
?>
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
0

Try this

$text = htmlspecialchars('<p class="hero big" style="color: inherit; border: none">Text <br />Text</p>', ENT_QUOTES);

$text = preg_replace('/\s+/', '~', $text);

echo $text;

Note:- Treat html tags and main text separately

vishal
  • 1,368
  • 2
  • 15
  • 34
0

Thanks to PHP preg_replace: how to replace text between tags?, here's a solution:

<?php
$s = '<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>';
$text = preg_replace_callback('#(<)([^>]+)(>)#', function($matches){
    return $matches[1].str_replace(" ", "~", $matches[2]).$matches[3];
}, $s);
?>
Community
  • 1
  • 1
Somerussian
  • 381
  • 4
  • 17
0

You can use (*SKIP)(*F) to skip outside tags like this:

$str = preg_replace('~>[^<]*(*SKIP)(*F)|\s+~','~', $str);

See demo at eval.in

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46