rn42v1r rn42v1r - 3 years ago 232
PHP Question

find and color a string in another string php

I have a String, let's say:

$needle = "HELLO";

And I have another String I want to find $needle in, let's say:

$haystack = "HELLO WORLD";

I know there are methods which return the position as an int etc.
but how could I then color that very string when it's being output?
I made myself an array with some chars in it which are being output randomly like 2000 times and I'd like to see them in color when they make up the right word.

Answer Source

I've interpreted your question as:

I want to find a string within another string, making the matching characters a different colour in the output

Easiest method would be

<style>.myclass { color: red; }</style>

$needle = "HELLO";
$haystack = "HELLO WORLD";

$myOutput = str_replace($needle,"<a class='myclass'>".$needle."</a>",$haystack);

echo $myOutput;


Obviously editing it to suit the method you're intending for it, but the above should help with one possible solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download