1

My output is wrong, I want the output to be as follows:

My CCC in my category. 

but This is the text that output :

My CCC in my CCCegory

This is the code I tried:

$text = "My cat in my category";
$searchVal = array("cat", "dog", "fish");
$replaceVal = array("CCC", "DDD", "FFF");
$strtext = str_replace($searchVal, $replaceVal, $text );
echo $strtext;

//output: My CCC in my CCCegory
2
  • 1
    If you're trying to match whole words only then add a space on each side of the search terms. Try $searchVal = array(" cat ", " dog ", " fish "); Commented Nov 10, 2021 at 8:52
  • 1
    @bassxzero that would fail though if the word is at the start or end of the text to be searched, unless you pad that text with spaces first. Commented Nov 10, 2021 at 8:53

1 Answer 1

1

I guess you can use regular expressions and test for word boundaries.

<?php
        
$text = "My cat in my category";
$searchVal = array("~\bcat\b~", "~\bdog\b~", "~\bfish\b~");
$replaceVal = array("CCC", "DDD", "FFF");
$strtext = preg_replace($searchVal, $replaceVal, $text);
echo $strtext;

//output: My CCC in my category
Sign up to request clarification or add additional context in comments.

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.