Arif Hidayat
Arif Hidayat

Reputation: 67

how to remove space and replace forward slash in php

i have variable

$var = "A/P/ 20014/03 /12/4098 "

space uncertain in variable how to remove space and replace forward slash. i want result like this "A-P-20014-03-12-4098"

Upvotes: 0

Views: 9999

Answers (4)

Kevin
Kevin

Reputation: 41885

A simple str_replace can do this:

$var = "A/P/ 20014/03 /12/4098 ";
$var = str_replace(array('/', ' '), array('-', ''), $var);
echo $var;

Illustration:

                        search for        replacement
$var = str_replace(array('/', ' '), array('-', ''), $var);
                          ^    ^           ^    ^
                          |----|-----------|    |
                               |----------------|

Upvotes: 6

Traian Tatic
Traian Tatic

Reputation: 691

Use this:

$var = "A/P/ 20014/03 /12/4098 ";
// / to -
$var = preg_replace("/\//",'-',$var);
// removes all the whitespaces
$var = preg_replace('/\s+/', '', $var);
echo $var;

Upvotes: 1

Kasper Sanguesa-Franz
Kasper Sanguesa-Franz

Reputation: 617

You can do something like this

$var = str_replace(array(" ","/"), array("","-"), $var);

It's possible to add a a array to str_replace with the chars/strings you want to replace.

If you want to replace more characters you can just add it to the arrays

Upvotes: 0

Jenz
Jenz

Reputation: 8369

$var = "A/P/ 20014/03 /12/4098 ";    // your string
$out = str_replace("/", "-", $var);  // replace all / with -
$string = preg_replace('/\s+/', '', $out);  // trim all white spaces

Upvotes: 0

Related Questions