Display part of string

Posted on 2011-05-10
Last Modified: 2012-05-11

I've got a string like so:
$str = "2008T(12)-1234P(13)-111T(12)-908P(45)-11T(11)";
I need to if chosen part exists, let's say
$part = "1234P";
and display it with number in brackets if exists, so
$final = "1234P(13)" in this case.
otherwise display "echo $part.' does not exists';".

Any ideas?
Thanks for any help.
Question by:Zado
    LVL 12

    Assisted Solution

    if $str = "2008T(12)-1234P(13)-111T(12)-908P(45)-11T(11)";
    and $part = "1234P";
    $pos1 = strpos($str,$part); // 10
    $len1 = strlen($part); //5
    $len2 = strpos($str,')',$pos1+1)-$pos1;  //19
    $final = substr($str,$pos1,$len2-$len1) //1234P(13)
    LVL 8

    Author Comment

    Thanks, but output of you script is "123" instead "1234P(13)"
    LVL 7

    Accepted Solution

    just to build on Amick's, I believe he made a slight mistake on his "$len2" equation. Try the following:

    $str = "2008T(12)-1234P(13)-111T(12)-908P(45)-11T(11)";
    $part = "1234P";
    $pos1 = strpos($str,$part); // 10
    $len1 = strlen($part); //5
    $len2 = strpos($str,')',$pos1+1)+1;  //19
    $final = substr($str,$pos1,$len2-$pos1); //1234P(13)
        echo "Final: $final";
        echo "$part does not exist";

    Open in new window

    if you use $part = "1234P", it will print "Final: 1234P(13)"
    if you use $part = "4321P", it will print "4321P does not exist"
    LVL 8

    Author Closing Comment

    Excellent, thanks.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Suggested Solutions

    Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
    Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
    The viewer will learn how to count occurrences of each item in an array.
    The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

    745 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

    15 Experts available now in Live!

    Get 1:1 Help Now