简体   繁体   中英

Find letters in paragraph via PHP

Let's say I have this sentence.

"The dog took the kid's bone."

Well using PHP, can I find specific letters inside that sentence (if any at all) that I specify?

So for example, I want to find the letters g, t, h, and e.

Then the sentence would appear like:

The do g -- t ook t h e kid's bon e .

(sorry about formatting...)

See how certain letters are bolded (highlight in a way). They are from the g,t,h, and e combo I wanted. Is there a way to do this in PHP?

Also, I forgot to mention that once a letter is found... it cannot be bolded again. So if I was looking for a t* and the letter t appeared more than once... it would ONLY highlight ONE (the first) t... UNLESS I specify to find more than one t.

A somewhat elegant solution could be:

$letters = array('/a/', '/p/', '/l/');// combo
$sentence = "The rain in Spain stays mainly on the lane.";
$sentence = preg_replace($letters, '<b>$0</b>', $sentence, 1);

Check the preg_replace documentation for more info on how this works.


As I said that was an elegant solution. This one works ;), but it's not pretty.

$letters = array('s', 'p', 'a', 'l', 'l', 'b');// combo
$sentence = "The rain in Spain stays mainly on the big lane.";
foreach($letters as $letter){
    $sentence = preg_replace('/(?<![\>\<\/])'.$letter.'|(?<=\<\/b\>)'.$letter.'/i', '<b>$0</b>', $sentence, 1);
}
echo $sentence;

Any reason you can't use simple search and replace for this?

$string = str_replace(array('g', 't', 'h', 'e'), array('<b>g</b>', '<b>t</b>', '<b>h</b>', '<b>e</b>'), $string);

or with a regular expression:

$string = preg_replace('/([gthe])/i', '<b>\\1</b>', $string);

Edit: Okay you added some stuff to the question. preg_replace has a limit parameter, so you can do something like this:

$string = preg_replace('/(g)/i', '<b>\\1</b>', $string, 1);

to just replace the first occurrence of 'g'. You'll need to do this in a loop if you have multiple strings (there may be a better way), and be careful not to replace the 'b' of <b> if that happens to be one of your letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM