我想从此字符串中删除最后一个数字(包括破折号):
你好世界-093
结果应该是:
你好世界
http://php.net/manual/en/function.preg-replace.php
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] );
在你的情况下应该是这样的:
$subject = 'hello-world-093' ;
$subject_stripped = preg_replace ( '/-[0-9]*$/' , '' , $subject);
上述模式将删除
-
以及字符串末尾后面的所有数字。
http://php.net/manual/en/function.strrpos.php
strrpos — 查找字符串中子字符串最后一次出现的位置
对字符
strrpos
执行 -
,您就知道结果将是字符串中 -
的最后一个位置。
现在,您可以通过使用 http://www.php.net/manual/en/function.substr.php 并提供您的位置作为长度来仅获取字符串的第一部分。
这是另一种方法。我提供的这不是最好的方法,而是剥猫皮的另一种方法。我认为了解解决问题并探索它们的方法有很多种,这一点很重要。通过学习从不同角度解决问题,您会学到很多东西。
祝你好运,希望这有帮助,
蒂姆·杜马斯
<?php
$pattern = "/^(.*)-[0-9]*$/";
$string = "hello-world-093";
preg_match($pattern, $string, $matches);
print_r($matches);
?>