PHP Preg-Replace more than one underscore

前端 未结 8 1372
难免孤独
难免孤独 2020-12-17 03:22

How do I, using preg_replace, replace more than one underscore with just one underscore?

相关标签:
8条回答
  • 2020-12-17 04:02

    preg_replace()

    the + operator is needed

    $text = "______";
    $text = preg_replace('/[_]+/','_',$text);
    
    0 讨论(0)
  • You can also use T-Regx library which has automatic delimiters.

    pattern('_+')->replace($your_string)->with('_');
    
    0 讨论(0)
  • 2020-12-17 04:07

    Actually using /__+/ or /_{2,}/ would be better than /_+/ since a single underscore does not need to be replaced. This will improve the speed of the preg variant.

    0 讨论(0)
  • 2020-12-17 04:15

    preg_replace('/[_]+/', '_', $your_string);

    0 讨论(0)
  • 2020-12-17 04:15

    I'm don't the reasons you want to use preg_replace but what's wrong with:

    str_replace('__', '_', $string);
    
    0 讨论(0)
  • 2020-12-17 04:16
    This will Accept Only Characters,numeric value or Special Character found it will replace with _
    <?php
    error_reporting(0);
    if($_REQUEST)
    {
        PRINT_R("<PRE>");
        PRINT_R($_REQUEST);
        $str=$_REQUEST[str];
        $str=preg_replace('/[^A-Za-z\-]/', '_', $str);
        echo strtolower(preg_replace('/_{2,}/','_',$str));
    }
    ?>
    <form action="" method="post">
    <input type="text" name="str"/>
    <input type="submit" value="submit"/>
    </form>
    
    0 讨论(0)
提交回复
热议问题