PHP: find value in a string

Posted on 2009-02-11
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
    LVL 107

    Expert Comment

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

    Accepted Solution


    $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

    LVL 2

    Author Comment


    I worked it out from the function you provided.

    Open in new window

    LVL 107

    Expert Comment

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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now