How can I remove part of a string in PHP? [closed]

Solution 1:

If you're specifically targetting "11223344", then use str_replace:

// str_replace($search, $replace, $subject)
echo str_replace("11223344", "","REGISTER 11223344 here");

Solution 2:

You can use str_replace(), which is defined as:

str_replace($search, $replace, $subject)

So you could write the code as:

$subject = 'REGISTER 11223344 here' ;
$search = '11223344' ;
$trimmed = str_replace($search, '', $subject) ;
echo $trimmed ;

If you need better matching via regular expressions you can use preg_replace().

Solution 3:

Assuming 11223344 is not constant:

$string="REGISTER 11223344 here";
$s = explode(" ", $string);
unset($s[1]);
$s = implode(" ", $s);
print "$s\n";

Solution 4:

str_replace(find, replace, string, count)
  • find Required. Specifies the value to find
  • replace Required. Specifies the value to replace the value in find
  • string Required. Specifies the string to be searched
  • count Optional. A variable that counts the number of replacements

As per OP example:

$Example_string = "REGISTER 11223344 here";
$Example_string_PART_REMOVED = str_replace('11223344', '', $Example_string);

// will leave you with "REGISTER  here"

// finally - clean up potential double spaces, beginning spaces or end spaces that may have resulted from removing the unwanted string
$Example_string_COMPLETED = trim(str_replace('  ', ' ', $Example_string_PART_REMOVED));
// trim() will remove any potential leading and trailing spaces - the additional 'str_replace()' will remove any potential double spaces

// will leave you with "REGISTER here"