trimming a string in php

安稳与你 提交于 2019-12-12 05:59:37

问题


i'm still quite new to programming, so please excuse me.

I need to do the following:

Right now i have a string being output with two value: one with characters and numbers, a comma and the second with just a boolean value.

9fjrie93, 1

I would like to trim the string so it just ourputs as the boolean value. e.g.

1

I then need to perform an equality check on the boolean value. If it's 1 do one thing, else do something else. Would a simple if statement suffuce?

Thanks very much


回答1:


No need for explode if it's always the last character.

<?php
$val = '9fjrie93, 1';
if( substr( $val, -1 ) === '1' ) {
    // do stuff.
}
else {
    // do stuff. Just other stuff.
}



回答2:


How about:

$vals = explode(", ", "9fjrie93, 1");
if ($vals[1]) ...



回答3:


You can also use list to name the results returned:

$original_str = '9fjrie93, 1';
list($characters, $boolean) = explode(', ', $original_str);
echo $boolean;



回答4:


Try this:

    $str = '9fjrie93, 1';
    $str = explode(', ', $str); //it returns array('9fjrie93', '1')
    $str = end($str); //takes the last element of the array



回答5:


$mystring = '9fjrie93, 1';
$findme   = ',';
$pos = strpos($mystring, $findme);
$i= substr($mystring,$pos);



回答6:


$string = "9fjrie93, 1";
$val = substr($string, (strrpos($string, ',')+1));

Don't use explode since it's slower




回答7:


If the 1 is always at the end of the line, you can do:

$line = '9fjrie93, 1'
if ( $line[strlen([$line])-1] == '1' ) {
    // do stuff
} else {
    // do other stuff
}

Which should at least perform better than explode, str_replace and substr solutions.




回答8:


$pos = strpos($source_str, ',');
substr($source_str, $x_pos + 1);

hope this will solve it.




回答9:


 $output = str_replace(',', '', strstr('9fjrie93, 1', ','));
 if( $output == '1' ) {
   ....do something
  } else {
  ...do something else
  }


来源:https://stackoverflow.com/questions/12531456/trimming-a-string-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!