PHP Deletes a space in a string multiple ways

Source: Internet
Author: User
Tags regular expression strlen trim

This tutorial provides a few PHP tutorials to remove a space in a string a variety of methods Oh, using the PHP function, Str_replace,trim, regular and so on to replace the space of the string effective method

A function with PHP itself

Str_replace ("", "", $str);
To replace

<?php
$str = "# #使用函数trim去掉字符串两端特定字符";
$str 1 = Trim ($str, "#"); Pass in the second argument for the function trim, trim will remove the string $str the # character at both ends
echo $str. " <br> ";
echo $str 1;
?>


Instance

<?php
$STR = "Use function trim to remove whitespace characters from both ends of the string";
$str 1 = Trim ($STR); echo "Before processing has". strlen ($STR). Characters ";
echo "<br/>";
echo "<br/>";
echo "processed with the Trim function". strlen ($str 1). Characters ";
?>

Look at a higher level.
PHP program Deletes "space" in "string element" in "array"

?
$arr =array ();
$arr []= "ad DFD DFD";
$arr []= "SAF SDF DSF";
$arr []= "SDF DSFGFD DD";
$arr []= "DFD dfferw";
while (list ($name, $value) =each ($arr)) {
Echo $value;
$arr 2[]=trim ($value);//Go to space
}
Print_r ($arr 2);//This should be the array you want.
?>

Try to remove a space with a regular expression

$string = Preg_replace ("/s+ ([rn$])/", "1", $string);

When ' $ ' is inside [], www.45it.net does not represent the ' end of string


---------------------------------------------------------------

$string = Preg_replace ("/s+ ([x20]|$)/", "1", $string);


---------------------------------------------------------------

$string = Preg_replace ("/x20+ ([rn]|$)/", "1", $string);


---------------------------------------------------------------

$string = Preg_replace ('/([RN]) [s]+/', ' 1 ', $string);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.