Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace spaces, comma's, dashs and ! with forward slashes

Tags:

php

So far I have :

$q = str_replace(' ','/',$q);
$q = str_replace(',','/',$q);
$q = str_replace('\-','/',$q);

but I'm not sure what I'm doing wrong because none of the PHP sites that explain the functions, include an example of every character to search for.

Note, I only want it to replace spaces, comma's ',' dashes '-', '!' with forward slashes and then another replace function to replace any '&' with 'and'.

like image 816
user1342903 Avatar asked Apr 19 '12 03:04

user1342903


2 Answers

Regular expression-free example:

$str = str_replace([' ', ',', '-', '!'], '/', '& String! - !');
$str = str_replace('&', 'and', $str);
echo $str;
like image 81
Mārtiņš Briedis Avatar answered Oct 17 '22 04:10

Mārtiņš Briedis


Try this :

$q = preg_replace('/[\s,\-!]/', '/', $q);

$q = str_replace("&","and",$q);
like image 22
Dr.Kameleon Avatar answered Oct 17 '22 03:10

Dr.Kameleon