how to remove chars into a string?
I have a lot of strings, and I need to delete '0' at start of string, but what is the better way to do it, because this is an example of strings:
0130799.jpg //I need to get 130799
0025460.jpg //I need to get 25460
Now, I'm using substr function, but I think it's more efficient if I'll use R开发者_开发技巧egex no ?
just type cast will do it efficiently
echo (int) $var;
If the format is the same for all strings ([numbers].jpg), you could do:
intval('0130799.jpg', 10);
intval() in Manual
With a regular expression you can just do
preg_replace('/^0+/m','',$sourcestring);
^
is the start of the string (here with the m
modifier the start of a row)
0+
means 1 or more zeros.
This regex will match all leading zeros and replace with an empty string.
See it here on Regexr
If you use substr
you have to use it in conjunction with strpos
because substr
needs to know string indexes.
Yes, you are better off with a regex.
If your question is how to extract the digits from a string 00000ddddddd.jpg (for some number of zeros and non-zero digits) anywhere in a string, then you should use preg_match.
Here is a complete example which you can try on http://writecodeonline.com/php/
preg_match('/([1-9][0-9]+)\.jpg/', "I have a file called 0000482080.jpg somewhere", $matches);
echo "I like to call it: {$matches[0]}";
If the entire string is a filename, then use intval
or casting as suggested in the other answers.
精彩评论