[英]Regex: Match words in sentence PHP
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")
但它应该只是它们完全匹配(例如“walk”应匹配“Walk”或“walk!”但不是“walk”)
And the replacement should be a simple link like: < a href='#walk' >walk< /a >
替换应该是一个简单的链接,如:
< a href='#walk' >walk< /a >
Anybody Any idea? 有人有什么想法吗?
To Match each words like "walk" but not "walking" Use \\b for word bounday. 匹配每个单词,如“walk”但不是“walk”使用\\ b进行单词bounday。
For Example, "\\bwalk\\b"
例如,
"\\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". 请注意,它匹配“go”和“walk”,但不匹配“walk”,并且在链接变为小写“#walk”时保持Walk上的大写字母W.
This way, "Walk walk WALK wALk" will all link to #walk without affecting the original formatting. 这样,“Walk walk WALK wALk”将链接到#walk,而不会影响原始格式。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.