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
Regular expression?
So assuming you want the number (and not the 4th word or something like that):
$str = preg_replace('#\D#', '', $str);
\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) :
$str = preg_replace('#.*?(\d{4,4}).*#', '\1', $str);
You can actually just pass the entire set of characters to be trimmed as a parameter to trim
:
$string = trim($string, 'abc...zABC...Z ' /* don't forget the space */);
精彩评论