PHP function is similar to this JavaScript function

I need a similar function in PHP for this JavaScript function

text = text.replace(/ffc/g, "Hello");

I think preg_replace will do, but I'm not sure how to write an expression.

I want a regular expression like the /ffc/gone above that I need to exactly match the full word and case when doing the replacement ...

+3
source share
5 answers
$text = preg_replace('/ffc/', 'replacement text',  $subject);

The online manual for PHP is pretty amazing, and one of the best features of the language:

http://php.net/preg_replace

+5
source

Just use str_replaceas follows:

$text = str_replace('ffc', 'Hello', $text);

Using regexp here is a huge abuse.

+1

preg_replace(); .

Explaination:

preg_replace  (  mixed $pattern  ,  mixed $replacement  ,  mixed $subject  [,  int $limit = -1  [,  int &$count  ]] )
The pattern to search for. It can be either a string or an array with

.

The e modifier makes preg_replace() treat the replacement

PHP . : , PHP, PHP , preg_replace().

. pattern , . , , . , , .

replacement may contain references of the form \\n or (since PHP 4.0.4)

$n, . , n- . N 0 99, \0 $0 , . ( 1), . ( "\\" PHP).

When working with a replacement pattern where a backreference is

( : ), \1 . \11, , preg_replace(), \1 backreference 1, \11 backreference, . \ ${1} 1. $1 backreference, 1 .

When using the e modifier, this function escapes some characters

( ', ",\ NULL) , _. (, 'STRLEN (\' $1\') + StrLen (" $2")'). , PHP , , .

.

If subject is an array, then the search and replace is performed on

, value .

.

, . -1 ( ).

preg_replace() , subject .

If matches are found, the new object will be returned, otherwise it will be returned unchanged or NULL if an error occurs.

0
source

Following your requirements for replacing the full word, I suggest the following:

$text = preg_replace ('/\bffc\b/', 'Hello', $text);

Replaces all instances of "ffc" and case sensitive

0
source
str_replace($needle, $replacement, $haystack);
-2
source

Source: https://habr.com/ru/post/1743451/


All Articles