Thursday, October 23, 2025
HomeLanguagesHow to remove portion of a string after a certain character in...

How to remove portion of a string after a certain character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character.
strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string. Function treats upper-case and lower-case characters differently.

Syntax:

strpos( original_string, search_string, start_pos )

Return Value: This function returns an integer value which represents the index of original_str where the string search_str first occurs.

substr() function: The substr() function is an inbuilt function in PHP is used to extract a specific part of string.

Syntax:

substr( string_name, start_position, string_length_to_cut )

Return Value: Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure.
Here are few examples.

Below examples use substr() and strpos() function to remove portion of string after certain character.

Example 1:




<?php
  
// Declare a variable and initialize it
$variable = "GeeksForGeeks is the best platform.";
  
// Display value of variable
echo $variable;
echo "\n";
  
// Use substr() and strpos() function to remove
// portion of string after certain character
$variable = substr($variable, 0, strpos($variable, "is"));
  
// Display value of variable
echo $variable;
  
?>


Output:

GeeksForGeeks is the best platform.
GeeksForGeeks

Example 2:




<?php
  
// Declare a variable and initialize it
$variable = "computer science portal for neveropen";
  
// Display value of variable
echo $variable;
echo "\n";
  
// Use substr() and strpos() function to remove
// portion of string after certain character
// and display it
echo substr($variable, 0, strpos($variable, "for"));
  
?>


Output:

computer science portal for neveropen
computer science portal
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS