Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find first character in string and return everything after.

Status
Not open for further replies.

monkey64

Technical User
Apr 27, 2008
69
GB
I have the string "MYPART0123456789"
I want to search it for the first occurance of a character within the range [0-9], and return everything after that (0123456789).

I have experimented with strstr, but I need to pattern match.
I know the code below won't work, but I can't get any further.

Code:
$pattern = preg_match('/^[A-Z]/', $s);
$s= 'MYPART0123456789';
echo strstr($s, $pattern);
 
Hi

Why not just remove the unwanted characters ?
Code:
[navy]$s[/navy][teal]=[/teal][green][i]'MYPART0123456789'[/i][/green][teal];[/teal]
[b]echo[/b] [COLOR=darkgoldenrod]preg_replace[/color][teal]([/teal][green][i]'/^[^0-9]*/'[/i][/green][teal],[/teal][green][i]''[/i][/green][teal],[/teal][navy]$s[/navy][teal]);[/teal]

Feherke.
 
but in the event that later characters can be alphanumeric too (unlikely given the OP's question but possible for future readers), this should work

Code:
$pattern = '/[\D]*(.*?)/';
preg_match($pattern, $text, $match);
echo $match[1];
 
Thanks for the examples. As my part codes are always in the pattern [A-Z], followed by [0-9], I'm going with feherke's excellent preg_replace example.

Had to take a first look at regex to undertstand the caret within the square brackets. I found a good site here:

Thanks again
 
just so that future readers understand the different approaches

Code:
[^0-9]*
is identical to
Code:
[\D]*
the difference between feherke's and my solution is:
+ feherke's simply removes all non digit representations, whereas my attempt captures the latter part of the string
+ due to the removal, my solution caters for ABCD19ABCD, capturing the 19ABCD.

 
Hi

Actually the [tt]\D[/tt] is a character class itself, so it not needs to be enclosed in brackets ( [] ). But your expression's problem is the non-greedy question mark ( ? ), which reduces the captured part to empty string.

Feherke.
 
you are completely correct viz the \D. i had originally gone for the [^\d] for better explainability. i missed removing the brackets.
and correct on the second point also, although I had intended to add a dollar sign to the end of the string.
sloppy of me: an inherent problem in providing solutions directly into tek-tips rather than via an IDE ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top