How to replace multiple items from a string in PHP

  1804 views   1 year ago PHP

Sometimes working with documents or large text, you might need to replace many characters in PHP. In PHP there is function str_replace function to replace words.

Syntax:

str_replace($search, $replace, $string, $count);

Where
$search is to be replaced with $replace in $string. $count is optional parameter that how many times to be replace.

Example:

<?php

$search = 'apple';
$replace = 'banana';
$string = 'I like to eat an apple with my dog in my chevy';

echo(str_replace($search, $replace, $string, $count));

// I like to eat an banana with my dog in my chevy

If you need to replace multiple character, pass the first two parameters as array that you want to replace.

<?php

$search = array('apple', 'dog', 'chevy');
$replace = array('banana', 'cat', 'jeep');
$string = 'I like to eat an apple with my dog in my chevy';

echo(str_replace($search, $replace, $string, $count));

// I like to eat an banana with my cat in my jeep

Hope you liked and it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]