Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder Coastal Web's Avatar
    Join Date
    Oct 2004
    Posts
    225
    Thanks
    12
    Thanked 3 Times in 3 Posts

    quick help with preg_replace?

    Hi guys, l have a few strings for example:

    testing+123
    testing+1+2+3

    What l'd like to do is strip off the + signs and anything after them,
    So in this example both strings would become 'testing'

    Can anyone help me with a preg_replace that would solve this problem for me?

    Regards,

  • #2
    Regular Coder
    Join Date
    Jul 2012
    Location
    London
    Posts
    473
    Thanks
    4
    Thanked 86 Times in 86 Posts
    PHP Code:
    <?php
    function myUrlEncode($string)
    {
        return 
    urlencode(str_replace'+' ' ' $string ));
    }
    ?>

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    That's the right idea, but not quite what they are looking for. Sounds like they want to remove everything to the right and including the first + sign.
    There are several ways. I'd use one of the ones below given the simple criteria:
    PHP Code:
    $aParts explode('+'$str);
    print 
    $aParts[0]; 
    Would be the easiest.
    PHP Code:
    $sFirst strtok($str'+');
    print 
    $sFirst
    Is another easy one and probably slightly better on memory.

    There are several ways to accomplish this; it is one of the pros of being a string based language. I would not recommend using pcre when you are simply striping based off of another character.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #4
    Regular Coder Coastal Web's Avatar
    Join Date
    Oct 2004
    Posts
    225
    Thanks
    12
    Thanked 3 Times in 3 Posts
    Thanks, l was specifically looking to do with preg_replace.
    Here's what the winning solution is:
    PHP Code:
        $str preg_replace('/\+.*$/'''$str); 

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    I'm not sure I understand why you want regex.
    Pattern matching is substantially slower than tokenizing by orders of magnitude (albeit we're talking about thousandths of seconds, but still).
    For such a simple match, its like swatting a fly with a sledgehammer.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •