我想在我的字符串(长文本)中替换与我数组中的单词匹配的单词
这是我的数组的样子:
array(
0 => "hello",
1 => "author",
2 => "cars",
)
这是我的字符串的样子:
Lorem ipsum dolor sit amet, cons etetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos e t accusam et jus to duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata s anctus est Lorem ipsum dolor hello sit amet. Lorem ipsum dolor sit a met, consetetur sadip scing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed di am voluptua. carsAt vero eos et accusam et justo duo dolores et ea rebum. Stet clita author, kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
这应该发生每个匹配(命名为MATCH)都应该像这样替换:
<a alt="MATCH" href="/link/MATCH">MATCH</a>
我试图解决这个问题几个小时,但我只是不知道如何想出解决方案…
如果后面没有空格,该词也应替换。
用你的话创造一个模式
方法一
$search = array(
0 => "hello",
1 => "author",
2 => "cars",
);
$replace = '<a alt="MATCH" href="/link/MATCH">MATCH</a>';
$patt = '/\b('.implode('|', $search).')/i';
$subject = preg_replace($search, $replace, $subject);
方法二
str_ireplace( $search, $replace, $subject);
方法2更简单,但不太有用,因为它更难反向引用匹配的单词。
如果您想要MATCH
或匹配的文本,有点困惑。如果您想要匹配的文本,请使用方法1和this进行替换
$replace = '<a alt="$1" href="/link/$1">$1</a>';
举个例子
https://regex101.com/r/pL4iA4/2
为了解释这是如何工作的,模式应该是这样的
'/\b(hello|author|cars)/i'
所以用简单的英语来说就是
\b
字边界(空格或特殊字符)()
括号捕获组|
或运算符/i
不区分大小写所以基本上捕获任何以单词列表
开头的单词
$text = // ...
$listOfPhrasesThatShouldBeLinks = [
'hello',
'author',
'cars'
];
$quotedListForRegex = array_map(
function ($phrase) {
return preg_quote($phrase);
},
$listOfPhrasesThatShouldBeLinks
);
$regex = '(' . implode('|', $quotedListForRegex) . ')/i';
$textWithLinks = preg_replace_callback(
$regex,
function (array $matches) {
$escapedMatch = htmlentities($matches[1]);
return '<a alt="' . $escapedMatch . '" href="/link/' . $escapedMatch . '">' . $escapedMatch . '</a>';
},
$text
);
你可以试试这个:
<?php
$a=array(
0 => "hello",
1 => "author",
2 => "cars",
);
$text = 'Lorem ipsum dolor sit amet, cons etetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos e t accusam et jus to duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata s anctus est Lorem ipsum dolor hello sit amet. Lorem ipsum dolor sit a met, consetetur sadip scing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed di am voluptua. carsAt vero eos et accusam et justo duo dolores et ea rebum. Stet clita author, kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
$text = str_ireplace($a,'<a alt="MATCH" href="/link/MATCH">MATCH</a>',$text);
echo $text;