Home > Backend Development > PHP Problem > How to replace spaces with newlines in php

How to replace spaces with newlines in php

青灯夜游
Release: 2023-03-08 18:42:01
Original
3222 people have browsed it

Replacement method: 1. Use the str_replace() function to replace, the syntax "str_replace(' ', "\n", $str)"; 2. Use the str_ireplace() function to replace, the syntax "str_ireplace( " ", "\n", $str)".

How to replace spaces with newlines in php

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

php replace spaces with newlines Method:

1. Use str_replace() function

<?php
$str = &#39;a b c&#39;;
// 空格替换成换行符(\n)
$str = str_replace(&#39; &#39;, "\n", $str);
// 显示字符
echo $str;
?>
Copy after login

Output:

a
b
c
Copy after login

Description:

str_replace() function replaces some characters in a string (case sensitive).

This function must follow the following rules:

  • If the searched string is an array, then it will return an array.

  • If the searched string is an array, then it will find and replace each element in the array.

  • If an array needs to be searched and replaced at the same time, and the elements to be replaced are less than the number of found elements, the excess elements will be replaced with empty strings .

  • If you search an array and replace only one string, the replacement string will work for all found values.

2. Use str_ireplace() function

<?php
$str = &#39;hello world !&#39;;
$search = " ";
$replace = "\n";
echo str_ireplace($search, $replace, $str);
?>
Copy after login

Output:

hello
world
!
Copy after login

Description:

str_ireplace () function replaces some characters in a string (case insensitive). The syntax is as follows:

str_ireplace(find,replace,string,count)
Copy after login

Parameter description:

  • find Required. Specifies the value to look for.

  • replace Required. Specifies the value to replace the value in find .

  • #string Required. Specifies the string to be searched for.

  • #count Optional. A variable counting the number of substitutions.

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to replace spaces with newlines in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template