简体   繁体   English

PHP rtrim 删除最后一个空格和后面的内容

[英]PHP rtrim to Remove the Last Space and What Follows

In PHP how to use trim() or rtrim() to remove the last space and the characters after?在 PHP 中如何使用 trim() 或 rtrim() 删除最后一个空格和后面的字符?

Expample:例子:

Any Address 23B任何地址 23B

to become成为

Any Address任何地址

AND

Another Address 6另一个地址 6

to become成为

Another Address另一个地址

You cant.你不能。 Trim is for spaces and tabs etc, or specified characters. Trim 用于空格和制表符等,或指定字符。 What you want is more specific logic.你想要的是更具体的逻辑。

If you want it from the last space:如果你想从最后一个空间得到它:

$lastSpace = strrpos($string, ' ');
$street = substr($string, 0, $lastSpace);
$number = substr($string, $lastSpace+1);

You can also implode on space, use array_pop to get the last value and then implode , but array functions on string manipulation are costly compared to a substr .您也可以在空间上内implode ,使用array_pop获取最后一个值,然后内implode ,但与substr相比,字符串操作的数组函数代价高昂。
You can also use a regex to get the last values, but while it's better than array manipulation for string, you should use it as a plan B as a regex isn't the most lightweight option either.您还可以使用正则表达式来获取最后一个值,但虽然它比字符串的数组操作要好,但您应该将其用作计划 B,因为正则表达式也不是最轻量级的选项。

Why don't you use a regex?你为什么不使用正则表达式?

$address = 'Any Address 23B';
$matches = [];
preg_match('/(?P<street>.*) \w+$/', $address, $matches);

print_r($matches['street']); // OUTPUT: "Any Address"

in case you dont wanna use the answers above, here is one solution without regex:如果您不想使用上面的答案,这里有一个没有正则表达式的解决方案:


$string = 'Any Address 23B';
$stringRev = explode(' ', strrev($string), 2);
echo strrev($stringRev[1]);  //result: Any Address

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM