Home >Backend Development >PHP Tutorial >How to Delete Text After a Specific Substring in PHP?

How to Delete Text After a Specific Substring in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 10:14:29439browse

How to Delete Text After a Specific Substring in PHP?

Deleting Text After a Specific Substring

Removing text from a string after a particular substring is straightforward in PHP. Consider the example string:

Posted On April 6th By Some Dude

If you wish to delete all characters, including and following the substring "By", follow these steps:

<code class="php">$variable = substr($variable, 0, strpos($variable, "By"));</code>

This code employs the substr(), and strpos() functions:

  • substr(): Accepts three parameters: the string, the starting position, and the ending position. In this case, we start from the beginning (0) and end at the position of the substring "By".
  • strpos(): Determines the position of the first occurrence of the substring "By" within the string.

Breaking this down in plain English:

Give me the portion of the string that starts from the beginning and ends at the point where you first encounter the substring "By".

Executing this code would result in:

Posted On April 6th

This method effectively removes everything after the specified substring.

The above is the detailed content of How to Delete Text After a Specific Substring in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn