Appearance
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:
How to remove portion of a string after a certain character in PHP?
php
<?php
$string = "Hello World!";
$character = "W";
$position = strpos($string, $character);
if ($position !== false) {
$newString = substr($string, 0, $position);
echo $newString; // Output: "Hello "
}
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
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 remain undefined.
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:
How to remove portion of a string after a certain character by using explode() function in PHP?
php
<?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 assigned the original $string value.