Sanitize sentence in php

后端 未结 2 406
半阙折子戏
半阙折子戏 2021-02-04 14:09

The title may sound odd, but im kind of trying to set up this preg_replace that takes care of messy writers for a textarea. It has to:

  1. if there is an exclamation s
相关标签:
2条回答
  • 2021-02-04 14:40
     - $result = preg_replace('/!+/', '!', $subject);
     - $result = preg_replace('/\.*,/', ',', $subject);
     - $result = preg_replace('/\s+(?=,)/', '', $subject);
     - $result = preg_replace('/^,*|,*$/', '', $subject);
     - $result = preg_replace('/([a-z])\1+/i', '$1$1', $subject);
     - $result = preg_replace('/,(?!\s)/', ', ', $subject);
    

    One by one matching to your rules :)

    0 讨论(0)
  • I might have to use this for my own sites... nice idea!

    <?php
    
    $text = 'My hooouse..., which is greeeeeen , is nice!!!  ,And pretty too...';
    
    $pats = array(
    '/([.!?]\s{2}),/', # Abc.  ,Def
    '/\.+(,)/',  # ......,
    '/(!)!+/',   # abc!!!!!!!!
    '/\s+(,)/',  # abc   , def
    '/([a-zA-Z])\1\1/', # greeeeeeen
    '/,(?!\s)/'); 
    
    $fixed = preg_replace($pats, '$1', $text);
    
    echo $fixed;
    echo "\n\n";
    
    ?>
    

    And the 'modified' version of $text: "My house, which is green, is nice! And pretty too."

    UPDATE: Here's the version that handles "abc,def" -> "abc, def".

    <?php
    
    $text = 'My hooouse..., which is greeeeeen ,is nice!!!  ,And pretty too...';
    
    $pats = array(
    '/([.!?]\s{2}),/', # Abc.  ,Def
    '/\.+(,)/',        # ......,
    '/(!)!+/',         # abc!!!!!!!!
    '/\s+(,)/',        # abc   , def
    '/([a-zA-Z])\1\1/');      # greeeeeeen
    
    $fixed = preg_replace($pats, '$1', $text);
    $really_fixed = preg_replace('/,(?!\s)/', ', ', $fixed);
    
    echo $really_fixed;
    echo "\n\n";
    ?>
    

    I would think this is a bit slower since it's an additional function call.

    0 讨论(0)
提交回复
热议问题