0

I want to match two string and if any words match I want to add tag to them.

I tried something like below below code

$old = "one two three";

$new = "how is one related to two";

foreach (explode(" ", $old) as $str) {
    $str .= str_replace($str, "<b>$new</b>", $str);
}
echo trim($str);

Exptected result how is <b>one</b> related to <b>two</b>.

Please suggest me some other way than looping if possible..If its not possible please tell me with looping.

0

5 Answers 5

2

Remember:

str_replace( look_for_this , replace_it_wtih_this, look_through_this);

In your code, you use .=, this will just copy a new sentence on every iteration. I would do it this way:

$old = "one two three";
$sentence = "how is one related to two";
$arr = explode(" ", $old);
foreach ($arr as $word) {
    $sentence = str_replace($word, "<b>$word</b>", $sentence);
}
echo trim($sentence);

Result:

how is <b>one</b> related to <b>two</b>
Sign up to request clarification or add additional context in comments.

2 Comments

hey thanks ! is it possible without loop ? I have to check like 1000 sentence in single page....or only loop is the way to go ?
The amount of text to check isn't the problem, the loop would just get more iterations by you adding more words to $old.
1

This is a way to do it, I think the mistake was using .= instead of = and also some mixed up parameters for str_replace() (PHP Sandbox)

$searchwords = "one two three";

$string = "how is one related to two";

foreach (explode(" ", $searchwords) as $searchword) {
    $string = str_replace($searchword, "<b>{$searchword}</b>", $string);
}

echo trim($string);

Comments

0

Try this:

foreach(explode(" ",$old) as $lol)
{
    $new = str_replace($lol, "<b>".$lol."</b>", $new);
}

Comments

0

Try using preg_replace instead of loop

<?php
$pattern = "/one|two|three/i";
$string = "how is one related to two";
$replacement = "<b>$0</b>";
$result = preg_replace($pattern, $replacement, $string);
echo $result;

Result will be

how is <b>one</b> related to <b>two</b>

You can check out preg_replace from here.

Comments

0

preg_replace for all:

function _replace($old,$new){
    $search = str_replace(' ',')|(',$old);
    return preg_replace("/($search)/i",'<b>$0</b>',$new);
}
echo _replace("one two three","how is one related to two");

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.