0

I got a simple php issue which is that I don't know how to use substring here...

ABCDEF[RAND NUMBER 1-10000000]GH

And so I need to get that random number using substring,

I dont know if my brain works correctly today but I really couldnt figure how to do that.

3
  • my expected output is as i said that random number. also i didnt tried any code because i have no idea how to do that Commented Apr 15, 2014 at 11:04
  • So you need 1-10000000 ? Commented Apr 15, 2014 at 11:06
  • Are the letters exactly as you wrote above, than you can go with strpos to determine the start and the end of the number by searching for "F" and "G". Otherwise I would go for an regular expression. Commented Apr 15, 2014 at 11:07

3 Answers 3

3

Regex is always better in this case but If your string pattern is fixed like ABCDEF123456GH, you can simply use substr like

$str = "ABCDEF432465GH";
echo substr($str, 6, -2);
Sign up to request clarification or add additional context in comments.

3 Comments

Why was this downvoted? This does exactly what the OP wants - extracts the random number from the string with offsets. As you may see the example in the question is rather stupid one not describing the context so it well may be there are other digits around the string, so this solution may be the only one correct as regexes mentioned above won't work.
Not to mention that performance wise string functions are times faster than regular expressions.
@CodeBird I am calm, mate, this is just one of those situations where a simple solution is considered bad/wrong by someone because it's simple, so I try to point people to be more mindful about it :)
3

This will do, no need for substr or anything:

$string='ABCDEF432465GH';
echo preg_replace('/[a-z\[\] ]*/i', '', $string);

https://eval.in/136918

1 Comment

@ICanHasCheezburger done, I didn't think that the [] are actually in there
3

Regular expressions are better when you don't know where in the text is desired substring,

$string = "ABCDEF10000000GH";

if (preg_match("/(\d+)/", $string, $m)) {
  print $m[1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.