替换字符串中除 PHP 之外的所有字符
我有一个字符串 Trade Card Catalog 1988 Edition
我希望删除除 1988 年以外的所有内容。
我可以拥有一个包含所有字母的数组,然后执行 str_replace
和 trim< /code>,但我想知道这是否是更好的解决方案?
$string = 'Trade Card Catalogue 1988 Edition';
$letters = array('a','b','c'....'x','y','z');
$string = str_to_lower($string);
$string = str_replace($letters, '', $string);
$string = trim($string);
提前致谢
I have a string Trade Card Catalogue 1988 Edition
I wish to remove everything apart from 1988.
I could have an array of all letters and do a str_replace
and trim
, but I wondered if this was a better solution?
$string = 'Trade Card Catalogue 1988 Edition';
$letters = array('a','b','c'....'x','y','z');
$string = str_to_lower($string);
$string = str_replace($letters, '', $string);
$string = trim($string);
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正则表达式?
因此,假设您想要数字(而不是第四个单词或类似的内容):
\D
表示每个不是数字的字符。与[^0-9]
相同。如果可能有更多数字,但您只想获得一个四位数字(一年),这也可以(但如果您有多个四位数字并且您想获得特定的一个,则显然会失败):
Regular expression?
So assuming you want the number (and not the 4th word or something like that):
\D
means every character that is not a digit. The same as[^0-9]
.If there could be more numbers but you only want to get a four digit number (a year), this will also work (but obviously fails if you there are several four digit numbers and you want to get a specific one) :
实际上,您可以将要修剪的整个字符集作为参数传递给
trim
:You can actually just pass the entire set of characters to be trimmed as a parameter to
trim
: