![](/img/trans.png)
[英]Using regex to match combination of words in the same in the same sentence in PHP
[英]Regex: Match words in sentence PHP
我有一個像數組一樣的數組
$arr = array("go", "walk", ...)
我想用句子中匹配的鏈接替換這些單詞。 但它應該只是它們完全匹配(例如“walk”應匹配“Walk”或“walk!”但不是“walk”)
替換應該是一個簡單的鏈接,如: < a href='#walk' >walk< /a >
有人有什么想法嗎?
匹配每個單詞,如“walk”但不是“walk”使用\\ b進行單詞bounday。
例如, "\\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");
這輸出:
'Lets <a href="#go">go</a> walking on a <a href="#walk">Walk</a>.'
請注意,它匹配“go”和“walk”,但不匹配“walk”,並且在鏈接變為小寫“#walk”時保持Walk上的大寫字母W.
這樣,“Walk walk WALK wALk”將鏈接到#walk,而不會影響原始格式。
嘗試這樣的事情:
$words = array('walk','talk');
foreach($words as $word)
{
$word = preg_replace("/\b$word\b/","< a href='#$word' >$word< /a >",$word);
}
我認為以下可能是你想要的。
<?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);
?>
但有幾點:
您的示例非常具體,因此很難准確確定您在實踐中需要匹配的內容(例如,您是否要在鏈接中包含'!'),但請嘗試以下操作:
<?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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.