Remove portion of a string after a certain character

There are several ways you can remove a portion of a string after a certain character in PHP. One way is to use the strpos function to find the position of the character in the string, and then use the substr function to extract the portion of the string before that character.

Here's an example:

<?php

$string = "Hello World!";
$character = "W";

$position = strpos($string, $character);
if ($position !== false) {
  $newString = substr($string, 0, $position);
  echo $newString; // Output: "Hello "
}

Watch a course Learn object oriented PHP

This will create a new string called $newString that contains everything from the beginning of $string up to the first occurrence of $character. If $character is not found in $string, $newString will be unchanged.

Another way to do this is to use the explode function to split the string into an array, and then use the array_shift function to remove everything after the first element:

<?php

$string = "Hello World!";
$character = "W";

$parts = explode($character, $string);
$newString = array_shift($parts);

echo $newString;

This will also create a new string called $newString that contains everything from the beginning of $string up to the first occurrence of $character. If $character is not found in $string, $newString will be unchanged.