How to trim text using PHP

前端 未结 5 1048
闹比i
闹比i 2020-12-21 01:54

How to trim some word in php? Example like

pid=\"5\" OR pid=\"3\" OR

I want to remove the last OR

相关标签:
5条回答
  • 2020-12-21 02:03

    You can try rtrim:

    rtrim — Strip whitespace (or other characters) from the end of a string

    $string = "pid='5' OR pid='3' OR";
    echo rtrim($string, "OR"); //outputs pid='5' OR pid='3'
    
    0 讨论(0)
  • 2020-12-21 02:06

    Using substr to find and remove the ending OR:

    $string = "pid='5' OR pid='3' OR";
    if(substr($string, -3) == ' OR') {
      $string = substr($string, 0, -3);
    }
    echo $string;
    
    0 讨论(0)
  • 2020-12-21 02:07

    I suggest using implode() to stick together SQL expressions like that. First build an array of simple expressions, then implode them with OR:

    $pids = array('pid = "5"', 'pid = "3"');
    
    $sql_where = implode(' OR ', $pids);
    

    Now $sql_where is the string 'pid = "5" OR pid = "3"'. You don't have to worry about leftover ORs, even when there is only one element in $pids.

    Also, an entirely different solution is to append " false" to your SQL string so it will end in "... OR false" which will make it a valid expression.

    @RussellDias' answer is the real answer to your question, these are just some alternatives to think about.

    0 讨论(0)
  • 2020-12-21 02:14

    What do you think about this?

    $str='pid="5" OR pid="3" OR';    
    $new_str=substr($str,0, strlen($str)-3);
    
    0 讨论(0)
  • 2020-12-21 02:21

    A regular expression would also work:

    $str = 'pid="5" OR pid="3" OR';
    print preg_replace('/\sOR$/', '', $str);
    
    0 讨论(0)
提交回复
热议问题