Jump to content

Recommended Posts

Is there an easy way to find a numeric value in a string if I don't know what the string will contain?

For example I want '52' out of: mystring52

 

Hopefully there is already a simple function to do this? I'm thinking there may not be as the string having more than one group of numbers may confuse matters. I'm just dealing with abcdef123 or similar in this case though.

 

 

Link to comment
https://forums.phpfreaks.com/topic/248160-find-numeric-value-in-string/
Share on other sites

You could use a regular expression.

I am horrible when it comes to regex but this at least works :)

$str = 'abc343def123';
preg_match_all('/[^a-zA-Z]{1,}/',$str,$matches);
echo '<pre>' , print_r($matches,true) , '</pre>'

/* Results in 
Array
(
    [0] => Array
        (
            [0] => 343
            [1] => 123
        )

)*/

 

Edit: even better

preg_match_all('/\d{1,}/',$str,$matches);

It would be nice if something like intval just worked
intval does work.  If you give it "potato123" intval says "that's not a number, so let's say zero." 

 

What happens if your string is "ab12cd34."  Do you want the number 1,234 or do you want two numbers?

Yeah I know what you mean.

 

What I'm wanting to do is pass a 'get' variable like ?page=thisone26

I can always do ?page=thisone&value=26 or something like ?page=thisone.26 and look for the separator.

 

Just thought my original layout was the nicest but it's looking like it's not worth the trouble!

 

"thisone26" is just in that form to look pretty I take it. There are two actual pieces of data, but because one is letters and the other is numbers you can combine them unambiguously.

 

Get the best of both worlds by using URL rewriting. You could use /page/thisone26 and

RewriteRule ^page/(\D+)(\d+)$ index.php?page=$1&value=$2 [L]

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.