How to implement word replacement in php

藏色散人
Release: 2023-03-10 20:48:02
Original
1647 people have browsed it

How to implement word replacement in php: first create a PHP sample file; then define a variable; finally implement the word through "preg_replace('/\bHello\b/', 'NEW', $text);" Just replace it.

How to implement word replacement in php

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

Specific questions:

How to implement word replacement in php? PHP string replace matches the whole word

I want to replace the whole word using php

Example:

If I have

$text = "Hello hellol hello, Helloz";
Copy after login

I use

$newtext = str_replace("Hello",'NEW',$text);
Copy after login

The new text should look like this

NEW hello1 hello, Helloz
Copy after login

PHP returns

NEW hello1 hello, NEWz
Copy after login

How to implement:

You want to use regular expressions. \b matches word boundaries.

$text = preg_replace('/\bHello\b/', 'NEW', $text);
Copy after login

If $text contains UTF-8 text, you must add the Unicode modifier "u" so that non-Latin characters are not misinterpreted as word boundaries:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);
Copy after login

Recommended learning:《PHP video tutorial

The above is the detailed content of How to implement word replacement in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!