PHP: find value in a string

Posted on 2009-02-11
Medium Priority
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
Question by:detox1978
  • 3
LVL 111

Expert Comment

by:Ray Paseur
ID: 23617704
You can use strrpos() to find the dash, and then use substr() to extract the number.
LVL 111

Accepted Solution

Ray Paseur earned 500 total points
ID: 23617734

$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


Author Comment

ID: 23617750

I worked it out from the function you provided.

Open in new window

LVL 111

Expert Comment

by:Ray Paseur
ID: 23617996
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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month15 days, 3 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question