简体   繁体   English

从字符串末尾删除特定字符之后的字符串部分

[英]Remove portion of a string after a particular character from the end of the string

I need to remove all characters from a string after a particular character from the end. 我需要从结尾删除特定字符后的字符串中的所有字符。 The below code works when it contains only one # eg: 下面的代码仅包含一个#时有效,例如:

$variable = "8233 Station #2212";
echo trim(substr($variable, 0, strpos($variable, "#")));

result: "8233 Station"; 结果:“ 8233站”; But if the string contains more than one # I need to avoid the strings after the last # 但是,如果字符串包含多个#,我需要避免最后一个#之后的字符串

 $variable = "8233 Station #2211 #2212";

The result i need in the above situation is "8233 Station #2211" 在上述情况下,我需要的结果是“ 8233 Station#2211”

Use strrpos to get position of last matching element 使用strrpos获取最后一个匹配元素的位置

//$variable = "8233 Station #2212"; //8233 Station
$variable = "8233 Station #2211 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#"))); //8233 Station #2211

It can also be done with substr() which extract the string from a string and strrpos() which return last occurrence of a character, try like below: 也可以使用substr()从字符串中提取字符串,然后使用strrpos()返回最后出现的字符,请尝试如下操作:

<?php
$variable = "8233 Station #2211 #2212";
echo substr($variable, 0, strrpos($variable, "#"));

check the output here: https://eval.in/813032 在此处检查输出: https : //eval.in/813032

Use strrpos instead of strpos 使用strrpos代替strpos

strpos — Find the position of the first occurrence of a substring in a string strpos —查找字符串中子字符串首次出现的位置

strrpos — Find the position of the last occurrence of a substring in a string strrpos —查找字符串中最后一次出现子字符串的位置

$variable = "8233 Station #2212 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#")));

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

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