quick preg_replace question ... need some help

by 6 replies
7
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,
#programming #php #preg_replace #pregreplace #question #quick #string
  • 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"
  • 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
    • [1] reply
    • 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!
      • [1] reply
  • Thanks all, l was specifically looking to do with preg_replace.
    Here's what the winning solution is:
    PHP Code:
         preg_replace('/+.*$/''', ); 
  • PHP Code:
    filter_var(, FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/+.*$/"))) 

Next Topics on Trending Feed