douping7975
2014-08-24 14:35
浏览 32
已采纳

在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

图片转代码服务由CSDN问答提供 功能建议

我有这个输入字符串:' - Adele Gislan - Web Developer - - - '
和预期的输出是这个字符串: Adele Gislan - Web Developer

我使用这个正则表达式

  $ urli =' -   -  Adele Gislan  - 网站开发人员 -   -   - '; 
 $ urli = preg_replace(“/ \  -  [[:space:]] + $ /”,“”,$ urli  ); 
 $ urli = preg_replace(“/ \  -  + $ /”,“”,$ urli); 
   
 
 

但是删除特殊字符“ - ” 或“ - ”只有一次。

我试试这个

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

但不理想

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongyan2445 2014-08-24 15:03
    已采纳

    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.
    打赏 评论
  • dongxie9448 2014-08-24 14:42

    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'
    
    打赏 评论
  • dongzhang7961 2014-08-24 14:54

    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
    
    打赏 评论
  • drbe16008 2014-08-24 15:00

    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

    打赏 评论

相关推荐 更多相似问题