2

I have string like

$text = "Hello :name its your :num_visit";

and Array

 $attr = [ ":name" => "Danny", ":num_visit" => 6];

I want to replace $text's patterns like :name, :num_visit with given values in array (Array have same key names).

Is it possible with php?

1
  • 1
    Have you tried something or did some research ? Commented May 13, 2015 at 10:53

3 Answers 3

2

Just use strtr() and pass the search/replacement array as second argument, .e.g

<?php

    $text = "Hello :name its your :num_visit";
    $attr = [":name" => "Danny", ":num_visit" => 6];
    echo strtr($text, $attr);

?>

output:

Hello Danny its your 6
Sign up to request clarification or add additional context in comments.

2 Comments

Its easier and better then other solution. Thank You
@user3720709: the main advantage is that strtr parses the string only once for all key/value pairs when str_replace parses the string for each key/value pair.
1

Use str_replace() to replace those. Pass the keys for search and values for replace -

$text = "Hello :name its your :num_visit";
$attr = [ ":name" => "Danny", ":num_visit" => 6];

echo str_replace(array_keys($attr), $attr, $text);

OUTPUT

Hello Danny its your 6

str_replace()

Working code

Comments

0

You can use str_replace().

$text = "Hello :name its your :num_visit";
str_replace( array(':name',':num_visit'), array('Danny','6'), $text );

:name will replace with Danny and :num_visit will replace with 6.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.