We help IT Professionals succeed at work.

PHP: find value in a string

detox1978
detox1978 asked
on
Medium Priority
626 Views
Last Modified: 2013-12-13
Hi All,

I need to set the numbers at the end of a string as a variable.  The number will always be at the end of the string and it will always be preseeded with a -

Example 1
$MyString = /index.php?page=/phil-117
$MyResult = 117


Example 1
$MyString = /index.php?page=/phil-11
$MyResult = 11


Many thanks
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
You can use strrpos() to find the dash, and then use substr() to extract the number.
Most Valuable Expert 2011
Author of the Year 2014
Commented:

<?php 
$str = '/index.php?page=/phil-117';
$pos = strrpos($str, '-');
if ($pos === FALSE) /* NO HYPHEN IN STRING */
$num = substr($str, $pos+1)

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks,

I worked it out from the function you provided.
strrev(substr(strrev($MyVariable),0,strpos(strrev($MyVariable),"-")));

Open in new window

Most Valuable Expert 2011
Author of the Year 2014

Commented:
Looks OK to me.  You might want some extra thought along the lines of "what if" - there could be more than one dash it if's user input, etc.  But given the test case, it looks fine.

Best regards, ~Ray
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.