Search

How to replace multiple items from a string in PHP

PHP
post-title

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.