Matúš Kočiš
Matúš Kočiš

Reputation: 23

remove special characters with regular expression in PHP

I have this input string: '- - Adele Gislan - Web Developer - - - '
and the expected output is this string: Adele Gislan - Web Developer

I use this regular expression

$urli='- - Adele Gislan - Web Developer - - - ';
$urli = preg_replace("/\-[[:space:]]+$/","",$urli);
$urli = preg_replace("/\-+$/","",$urli);

But this remove special character "-" or "- " only one time.

I try this

$urli = rtrim($urli, '-');
$urli = ltrim($urli, '-');

but isnt ideal

Upvotes: 0

Views: 288

Answers (4)

Tom Fenech
Tom Fenech

Reputation: 74645

If you just want to trim leading and trailing dashes and spaces, there's no need to use regular expressions. You could use one call to trim:

echo trim($urli, '- ');

The second argument is a list of characters to be removed.

Output:

Adele Gislan - Web Developer

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174716

You need to include the space and - symbol inside a character class,

^[ -]+|[ -]+$

Just replace the matched characters with an empty string.

DEMO

PHP code would be,

<?php
$mystring = "- - Adele Gislan - Web Developer - - - ";
echo preg_replace('~^[ -]+|[ -]+$~', '', $mystring);
?>

Output:

Adele Gislan - Web Developer

Explanation:

  • ^ Asserts that we are at the start.
  • [ -]+ Matches one or more space or - characters.
  • | Logical OR operator which is usually used to combine two regexes.
  • [ -]+ Matches one or more space or - characters.
  • $ Asserts that we are at the end of the line.

Upvotes: 1

Emissary
Emissary

Reputation: 10148

I'd be extra-greedy and simply match word bounds:

$str = ' - - Adele Gislan - Web Developer - - -';
$str = preg_replace('/.*?(\b.+\b).*/', '$1', $str);

» fiddle
» regex explanation

Upvotes: 0

Andie2302
Andie2302

Reputation: 4897

To get from:

 - - Adele Gislan - Web Developer - - - 

to

Adele Gislan - Web Developer

use:

[ -]{4,}

php-preg:

'/[ -]{4,}/m'

Alternatively you could use:

(?: *-+ *){2,}

php-preg:

'/(?: *-+ *){2,}/m'

Upvotes: 0

Related Questions