quick preg_replace question ... need some help

by dwoods
6 replies
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,
#php #preg_replace #pregreplace #question #quick #string
  • Profile picture of the author Brandon Tanner
    Instead of using regex, I would just do this...

    $string = "testing+123";
    $stringArray = explode("+", $string); // convert the string into an array, separated by the "+" delimiter
    $result = $stringArray[0]; // $result returns the value of the first item in the array, which is "testing"
    Signature

    {{ DiscussionBoard.errors[7642900].message }}
  • Profile picture of the author David V
    I agree with Brandon Tanner, don't need to use regex.

    You can also try:
    PHP Code:
    <?php
     
    "Testing+1+2+3";
     = 
    substr(, 0stripos(, "+") );
    // Find the "+" and return first part of string

    echo ;
    ?>
    The last line is being stripped when posting the code, but should read echo $finalresult;

    and another variation:

    PHP Code:
    <?php
     
    'Testing+1+2+3'
     = 
    strpos(, '+'); 
    if ( !== 
    FALSE) { 
       = 
    substr(, 0, ); 
    //Remove anything after the + character if present.

    echo ;  
    ?>
    The last line is being stripped when posting, but should read echo $customstring;

    stripos
    PHP: stripos - Manual

    substr
    PHP: substr - Manual

    explode
    PHP: explode - Manual

    Test them quick
    Test run php code
    {{ DiscussionBoard.errors[7643324].message }}
    • Profile picture of the author Brandon Tanner
      Originally Posted by David V View Post

      The last line is being stripped when posting the code
      Yeah, for some reason the forum strips out all PHP variables that are inside 'PHP' tags or 'CODE' tags. It kinda defeats the purpose of having those tags!
      Signature

      {{ DiscussionBoard.errors[7643460].message }}
      • Profile picture of the author David V
        Originally Posted by Brandon Tanner View Post

        ....It kinda defeats the purpose of having those tags!
        I know! I should have just posted like you did.... but I really like that "pretty" syntax highlighting
        {{ DiscussionBoard.errors[7643891].message }}
  • Profile picture of the author dwoods
    Thanks all, l was specifically looking to do with preg_replace.
    Here's what the winning solution is:
    PHP Code:
         preg_replace('/+.*$/''', ); 
    {{ DiscussionBoard.errors[7643998].message }}
  • Profile picture of the author oldschoolwarrior
    PHP Code:
    filter_var(, FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/+.*$/"))) 
    {{ DiscussionBoard.errors[7645119].message }}

Trending Topics