Hello Universe
Hello Universe

Reputation: 3302

Remove space from regex expression in php

I have a php echo with regular expression as in

echo preg_replace("/(\[|\])/", '', $paramValue);

I also want to make sure that any spaces are replaced aka if we have hello / world it becomes hello/world

I am not good with regex

Upvotes: 0

Views: 54

Answers (4)

abc123
abc123

Reputation: 18753

Regex

(\[|\]| )

PHP

echo preg_replace("/(\[|\]| )/", '', $paramValue);

Description

1st Capturing group (\[|\]| )
    1st Alternative: \[
        \[ matches the character [ literally
    2nd Alternative: \]
        \] matches the character ] literally
    3rd Alternative:  
        matches the character   literally

Upvotes: 0

Hello Universe
Hello Universe

Reputation: 3302

Thanks this is what I did

            utag_data.ad_sec<?php echo ($i+1); ?> = "<?php 
                preg_replace("/(\[|\]) /", '', $paramValue);
                $paramValue = str_replace(' ', '', $paramValue); 
                echo $paramValue;
            ?>";

Upvotes: 0

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Try this for removing space using regular expression.

$string = "hello / world";
$string = preg_replace('/\s+/', '', $string);
echo $string;

result:

hello/world

Upvotes: 0

Jay Bhatt
Jay Bhatt

Reputation: 5651

Try this.

For just space you can use:

$string = str_replace(' ', '', $string);

For whitespaces you can use:

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

Upvotes: 1

Related Questions