Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - String manipulation remove spcial characters and replace spaces

Tags:

string

php

I am getting strings from a database and then using the strings to build a URL. My issue is, some of the strings will have characters like < > & { } * general special characters, but the string may also have strings in. How would I replace the spaces with dashes and totally remove and special characters from the strings?

like image 390
sea_1987 Avatar asked Dec 03 '22 10:12

sea_1987


2 Answers

Keep only alphabets and numbers in a string using preg_replace:

$string = preg_replace('/[^a-zA-Z0-9-]/', '', $string);

You can use str_replace to replace space with -

$string = str_replace (" ", "-", $string);

Look at the following article:

  • How To Clean Special Characters From PHP String
like image 59
Naveed Avatar answered Jan 05 '23 04:01

Naveed


With str_replace:

$str = str_replace(array(' ', '<', '>', '&', '{', '}', '*'), array('-'), $str);

Note:

If replace has fewer values than search, then an empty string is used for the rest of replacement values.

like image 27
Felix Kling Avatar answered Jan 05 '23 06:01

Felix Kling