fork download
  1. <?php
  2.  
  3. // START WITH THIS TEXT
  4. $string = '<p style="font-size: 1.5em; color: navy;">
  5. Text With Spaces
  6. <p style="font-size: 1.2em; color: navy;"> ';
  7.  
  8. // LOOK FOR AN OPENING TAG, FOLLOWED BY A SPACE AND
  9. // - STRIP OUT ANY WHITESPACE AFTER IT
  10. $string = preg_replace_callback('~<([A-Z]+) \K(.*?)>~i', function($m) {$replacement = preg_replace('~\s*~', '', $m[0]); return $replacement;}, $string);
  11.  
  12. print $string;
  13.  
  14.  
  15.  
  16. print "\n\n";
  17.  
  18.  
  19. // HERE IS A MORE ADVANCED STRING WITH MULTIPLE SETS OF QUOTES AND OTHER TAGS THAT MAY NOT HAVE QUOTES
  20. $string = '<p style="font-size: 1.5em; color: navy;"><a href="http://www.google.com" style="color: orange;">Google Website</a>
  21. Text With Spaces
  22. <p style=\'font-size: 1.2em; color: navy;\'> <img src="http://www.google.com/images/logo.gif" width=100 height=100>';
  23.  
  24. // IF WE RUN THE SAME FUNCTION AS BEFORE, WE GET SOME MESSED UP TAGS
  25. $string = preg_replace_callback('~<([A-Z]+) \K(.*?)>~i', function($m) {$replacement = preg_replace('~\s*~', '', $m[0]); return $replacement;}, $string);
  26.  
  27. print $string;
  28.  
  29.  
  30.  
  31. print "\n\n";
  32.  
  33.  
  34.  
  35. // LET'S TRY THIS AGAIN, BUT APPLY A LITTLE MORE LOGIC TO IT
  36. $string = '<p style="font-size: 1.5em; color: navy;"><a href="http://www.google.com" style="color: orange;">Google Website</a>
  37. Text With Spaces
  38. <p style=\'font-size: 1.2em; color: navy;\'> <img src="http://www.google.com/images/logo.gif" width=100 height=100>';
  39.  
  40.  
  41. $string = preg_replace_callback('~<(.*?)>~i',
  42.  
  43. function($m) {
  44.  
  45. $return_var = preg_replace_callback('~\'|".*?\'|"~', function ($r) {$v = preg_replace('~\s*~', '', $r[0]); return $v;}, $m[0]);
  46. return $return_var;
  47. },
  48.  
  49. $string);
  50.  
  51. print $string;
  52.  
  53.  
  54. // THAT SEEMS RIGHT
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
<p style="font-size:1.5em;color:navy;">
 Text With Spaces
<p style="font-size:1.2em;color:navy;"> 

<p style="font-size:1.5em;color:navy;"><a href="http://www.google.com"style="color:orange;">Google Website</a>
 Text With Spaces
<p style='font-size:1.2em;color:navy;'> <img src="http://www.google.com/images/logo.gif"width=100height=100>

<p style="font-size: 1.5em; color: navy;"><a href="http://www.google.com" style="color: orange;">Google Website</a>
 Text With Spaces
<p style='font-size: 1.2em; color: navy;'> <img src="http://www.google.com/images/logo.gif" width=100 height=100>