Home >Backend Development >PHP Problem >How to remove characters before and after a string in php

How to remove characters before and after a string in php

青灯夜游
青灯夜游Original
2022-05-07 20:32:583218browse

Removal method: 1. If the characters before and after are the same, you can use trim() to remove them. The syntax is "trim(string, "character")"; 2. If the characters before and after are not the same characters, you can use ltrim( ) and rtrim() to remove respectively, the syntax is "ltrim(rtrim(string,'last character'),'previous character')".

How to remove characters before and after a string in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php removes strings Methods for characters before and after

1. If the characters before and after the string are the same, you can use the trim() function to remove

## The #trim() function removes whitespace characters or other predefined characters from both sides of a string. Syntax format:

trim(string,charlist)

  • string: Specifies the string to be checked.

  • charlist: Specifies which characters to delete from the string.

Return value: Return the modified string.

Example: Remove the a characters before and after the string

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = "a123456789a";
echo "原字符串:".$str;
echo "<br>去掉字符后:".trim($str,"a");
?>

How to remove characters before and after a string in php

2. If the characters before and after the string are not the same, you can use ltrim () and rtrim() functions respectively remove

  • The ltrim() function can remove whitespace characters or other preset characters on the left side of the string. Define characters.

  • The rtrim() function can remove whitespace characters or other predefined characters on the right side of a string.

The syntax of the ltrim() and rtrim() functions is similar to the trim() above and can be used for reference.

Example: Remove the a character in front of the string and the b character in the back

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = "a123456789b";
echo "原字符串:".$str;
echo "<br>去掉字符后:".ltrim(rtrim($str,&#39;b&#39;),&#39;a&#39;);
?>

How to remove characters before and after a string in php

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to remove characters before and after a string 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