我有一个关于替换字符串的非常简单的PHP问题。
例如,我们的字符串是:This is a test - spam text
我需要把这个字符串转换成这个:
This is a test
我的意思是我想检测-
字符的位置并删除之后的所有内容。
怎么做?
一个可能的解决方案:
$result = substr($str, 0, strpos($str, '-'));
使用substr返回字符串的一部分,使用strpos查找子字符串在字符串中第一次出现的位置
$str = 'This is a test - spam text';
$newStr = substr($str, 0, strpos($str, '-'));
// start ^ end ^
Try
$str = "This is a test - spam text";
$str = substr($str, 0, strpos( $str, '-'));
strpos()
检测-在哪里
您可以使用正则表达式匹配-字符之后的任何内容。
应该可以
/-.*/
当您匹配字符串时,您可以使用简单的字符串函数替换内容。