remove a character from a string in php

There are multiple ways to remove a character from a string in PHP. Here are two common approaches:

  1. Using substr function:
main.php
$string = 'Hello World!';
$character_to_remove = 'o';

$position = strpos($string, $character_to_remove);
if ($position !== false) {   // check if character exists in the string
    $new_string = substr_replace($string, '', $position, strlen($character_to_remove));
    echo $new_string;   // Output: Hell World!
}
315 chars
9 lines
  1. Using str_replace function:
main.php
$string = 'Hello World!';
$character_to_remove = 'o';

$new_string = str_replace($character_to_remove, '', $string);
echo $new_string;   // Output: Hell Wrld!
159 chars
6 lines

Note that both approaches will remove all occurrences of the specified character in the string. If you want to remove only the first occurrence, you can modify the code accordingly.

gistlibby LogSnag