Home>Article>Backend Development> How to implement word replacement in php

How to implement word replacement in php

藏色散人
藏色散人 Original
2021-06-24 11:37:43 1604browse

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";

I use

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

The new text should look like this

NEW hello1 hello, Helloz

PHP returns

NEW hello1 hello, NEWz

How to implement:

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

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

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);

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!

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