5

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 Regex no ?

bahamut100
  • 1,795
  • 7
  • 27
  • 38
  • As to the efficiency of a regex over another method see: http://stackoverflow.com/questions/3303355/substring-match-faster-with-regular-expression – Kevin Burton Jul 13 '11 at 07:22

4 Answers4

11

just type cast will do it efficiently

echo (int) $var;
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
3

If the format is the same for all strings ([numbers].jpg), you could do:

intval('0130799.jpg', 10);

intval() in Manual

kapa
  • 77,694
  • 21
  • 158
  • 175
0

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.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
0

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

stema
  • 90,351
  • 20
  • 107
  • 135
  • As say to Ray Toal answer : This way is ok for "000AA00" string ? "AA00" in result ? – bahamut100 Jul 13 '11 at 07:40
  • @bahamut100 I added a link to a regex test tool where you can see it. Yes it will also remove the leading 0 from "000AA00", is it this what you want? – stema Jul 13 '11 at 07:52