在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

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.

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'

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

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