Jump to content

How to capture the first number along with all text after it in string


Recommended Posts

I'm looking for a way to find and capture the first number and all text after it in a string.

 

Examples:

 

I have the following entries:

 

some text 23 text

sometext 21

sometext some text 120 text

 

I want the script to capture the number, and everything after it, and put it into a variable. At the same time, the captured part should be removed from the original string.

 

So the above examples whould be:

 

some text 23 text >> some text | 23 text

sometext 21 >> sometext | 21

sometext some text 120 text >> sometext some text | 120 text

 

How can this be done? I was suggested to use preg_match, but i can't figure out how to write that to do what I want.

Regular expressions? Take a walk on the wild side!

$len = strcspn($string, "1234567890");
$left = substr($string, 0, $len);
$right = substr($string, $len);
Consider trim()ing the two values too.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.