php/ regex/ arrays/ string

I have an array with words like

$arr = array("go", "walk", ...)

I would like to replace these words with links f they are matched in sentences. But it should be only if they match exactly (for example "walk" should match "Walk" or "walk!" but not also "walking")

And the replacement should be a simple link like: < a href='#walk' >walk< /a >

Anybody Any idea?

To Match each words like "walk" but not "walking" Use \\b for word bounday.

For Example, "\\bwalk\\b"

function magicWords($words, $string) {
  $from = $to = array();
  foreach($words as $word) {
    $from[] = "/\b$word\b/i"; // \b represents a word boundary
    $to[] = '<a href="#' . strtolower($word) . '">${0}</a>';
  }

  return preg_replace($from, $to, $string);

}

$words = array('go', 'walk');

echo magicWords($words, "Lets go walking on a Walk");

This outputs:

'Lets <a href="#go">go</a> walking on a <a href="#walk">Walk</a>.'

Note that it matches "go", and "walk", but not "walking", and maintains the capital W on Walk while the link becomes lower case "#walk".

This way, "Walk walk WALK wALk" will all link to #walk without affecting the original formatting.

Try something like this:

$words = array('walk','talk');

foreach($words as $word)
{
    $word = preg_replace("/\b$word\b/","< a href='#$word' >$word< /a >",$word);
}

I think the following might be what you want.

<?php
$someText = 'I don\'t like walking, I go';
$words = array('walk', 'go');
$regex = '/\\b((' . implode('|',$words) . ')\\b(!|,|\\.|\\?)?)/i';
echo preg_replace_callback(
    $regex,
    function($matches) {
        return '<a href=\'' . strtolower($matches[2]) . '\'>' . $matches[1] . '</a>';
    },
    $someText);
?>

A few of points though:

Your examples are quite specific, so it's hard to know exactly what you need to match in practice (eg do you want to include the '!' in the link?), but try this:

<?php

$text = "Walk! I went for a walk today. I like going walking. Let's go walk!";
$needles = array('go', 'walk');

foreach ($needles as $needle)
  $text = preg_replace('/\b(' . $needle . ')\b/i', '<a href="#' . $needle . '">$1</a>', $text);

print $text;

暂无
暂无

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.

Related Question Using regex to match combination of words in the same in the same sentence in PHP PHP Regex to match word in a sentence with optionally only other certain words Match words in file with regex php PHP match specific letters of sentence and get only the words PHP RegEx: How to extract certain words from a sentence? php regex match any number of words PHP match multiple whole words in regex Regex in PHP to match words with some excepetions PHP Regex to match a list of words against a string Match multiple whole words with regex with php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM