0

with this code I remove every spaces in a string.

public function callback_register_settings_remove_spaces( $input ) {

        // New Input
        $new_input = array();
        $new_input = $input;

        // Sanitize the input actually
        $new_input = preg_replace("/\s+/", " ", $new_input);

        // Sanitize the input actually
        $new_input = str_replace(" " , "" , $new_input);

        return $new_input;

    }

But, I need to NO REMOVE spaces if in a string exists a substring like this:

<script async src

So, if initial string is:

<script async src="http">Bla.js</script>
<script>window.dataLayer = window.dataLayer;</script>

Need to be:

<script async src="http">Bla.js</script><script>window.dataLayer=window.dataLayer;</script>

And not

<scriptasyncsrc="http">Bla.js</script><script>window.dataLayer=window.dataLayer;</script>

Thank you

sineverba
  • 5,059
  • 7
  • 39
  • 84
  • I don't know the bigger picture, but you might want to NOT remove spaces from strings inside quotation marks. – FirstOne Nov 21 '17 at 11:49
  • I don't know the bigger picture, but you might want to use a DOM parser if you are trying to handle HTML/XML – Gordon Nov 21 '17 at 11:50
  • As I'm really bad at *regular expressions* I'd do something like `explode` the string with your `$substring` as *delimiter*, then `str_replace` spaces, then loop through the exploded string values and `echo $substring . array[$value]`. But I know it's by far the worst working way to achieve it. – AymDev Nov 21 '17 at 11:57

3 Answers3

0

Remove the linebreaks then?

EDIT: Ah! Didn't see those spaces near your "="-sign. For linebreaks this still works. In your case it might not though. Sorry!

preg_replace( "/\r|\n/", "", $yourString );

Source on Stackoverflow

Akaino
  • 1,025
  • 6
  • 23
0

Some kind of syntax parser would be good here.

Here's a quick example of one possibility (a very crude one):

function minimizeJs($value)
{
    $output = '';

    $i = 0;
    // Iterate thru all TAGs by starting <
    while (($o = strpos($value, '<', $i)) !== false) {
        // There's a match between two TAGs, strip spacing
        if ($i < $o) {
            $output .= preg_replace('/\s+/', '', trim( substr($value, $i, $o - $i) ));
        }
        // Find end of this current TAG (>)
        $i = strpos($value, '>', $o) + 1;
        // Concat the TAG content
        $output .= substr($value, $o, $i - $o);
    }

    return $output;
}

This example is for special cases where data begins with a TAG and ends with a TAG. Parsing data before and after matches need to be added if used for other cases.

EDIT: This will explode if JS contains < or >.

Niko Hujanen
  • 743
  • 5
  • 10
-1

You can use trim(), see about this here http://php.net/manual/pt_BR/function.trim.php, u can use ltrim() for remove left spaces and rtrim() to.