PHP在foreach循环中替换仅替换数组列表中的最后一项

时间:2018-12-28 11:30:48

标签: php str-replace

我的问题是替换链接上下文中的关键字

<?php
$keywords = file("Keywords.txt"); 
shuffle($keywords);

$FullContent = "Owning a home sure is great but it also comes with plenty of responsibilities. There are times when no matter how diligent you've been, a home repair is necessary. On occasions like this, a lot of homeowners like to tackle the repairs on their own. Still there are some fixes you shouldn't take on yourself, since just a tiny mistake can end up costing you a real fortune. With this in mind, we have come up with 5 home repairs you should always leave to professionals.
Plumbing

A routine running toilet may be an easy fix, but when facing most of the other plumbing issues, turning to professionals is a much better option. Even if you have some plumbing experience and can identify the problem, tackling it yourself is never recommended. This is simply due to the fact that professional plumbers have all the necessary tools and know exactly what to do in case something goes wrong. On the other hand, if more unexpected issues arrive while you're doing a repair, it can all turn into a real river of trouble.
Roof Issues

Improper flashing, missing shingles, and damage caused by falling debris or harsh weather are just some of the roof issues you might experience. No matter which of them you face, chances are you'll be tempted to bring your ladders and start the repair on your own. Still, improper repairs can lead to some other issues such as mold, rot, and mildew. Not to mention that there's always danger of you falling down and getting injured. And this can all be avoided if you just call in local roof specialists and stay on the ground.
Ceiling

Many people believe that a simple patch may be enough to deal with cracks and holes in their ceiling but this never turns out to be a good idea. Just take a look at it this way - patching a crack or a hole in your ceiling won't do more help than applying a band aid to a real gunshot wound would. The cause of any ceiling issue in your home needs to be tracked down so that you can find the best solution for it. This is always better left to professionals who have seen plenty of issues like this and know exactly what to look for. Not only this, but they will also be able to advise you on the best and least expensive way for dealing with it.
Electrical Issues

There's no need to say that most electrical issues one can experience should never be handled by amateur electricians. No matter if it's a glitch with electrical supply, overloaded circuit, exposed or corroded electrical wires, contacting your local electrician is always a much safer option. Just the risk of electrocution is a reason enough not to try and do some repairing on your own. Dire situations call for an electrician that deals with those sort of things on a daily basis, such as an emergency electrician from Staywired Electrical, for example.
Gas appliances

A standard home has a couple of appliances that run on gas. Your oven, water heater, and clothes dryer are a few. If anything was to go wrong with these appliances or you simply want to have them replaced, turning to the pros is always recommended. This is the case because even if you manage to repair it yourself, there are always chances of you not hooking it up properly once the repair is made, and put yourself and your family at risk of carbon monoxide poisoning.

There are some easy home repairs that DIY enthusiasts can tackle but these 5 are none of them. No matter which of the issues described above you face, make sure you have professionals deal with it for you, even if means spending a buck or two";

foreach($keywords as $keyword) {
	$FullContent = str_replace($keyword, " <a href='https://www.google.com/search?num=100&source=hp&q=".$keyword."'>$keyword</a> ",$FullContent);
}
		
echo $FullContent;

问题是只能替换列表中的最后一个关键字

Keywords.txt包含:

home
electrical
water
gas

3 个答案:

答案 0 :(得分:4)

  

file

     

注意
  除非使用FILE_IGNORE_NEW_LINES,否则结果数组中的每一行都将包含行尾。

     

http://php.net/file

您的关键字不匹配,因为它们包含\n。添加FILE_IGNORE_NEW_LINES标志。

答案 1 :(得分:1)

正如Deceze指出的那样,您的问题是您试图将关键字与尾随换行符匹配。

我个人想只替换单词(考虑单词边界)。另外,模式检测可能需要对大小写不敏感,因为交换不会更改现有大小写。

<?php    

/*
Contents of things.txt:
cat
dog
mink
cow
*/

$keywords = file('/tmp/things.txt', FILE_IGNORE_NEW_LINES);

$text = "
A cow is a nice animal.  A bobcat is a kind of wild Cat.
";

foreach($keywords as $keyword) {
    $text = 
    preg_replace(
        "#\b($keyword)\b#i",
        "<a href='https://www.google.com/search?q=$keyword'>$1</a>",
        $text
    );
}

echo $text;

输出:

A <a href='https://www.google.com/search?q=cow'>cow</a> is a nice animal.  A bobcat is a kind of wild <a href='https://www.google.com/search?q=cat'>Cat</a>.

答案 2 :(得分:0)

使用str_replace做到这一点的方法是:

$arr_src = [];
$arr_rpl = [];
foreach($keywords as $keyword) {
    $arr_src[] = $keyword;
    $arr_rpl[] = "<a href='https://www.google.com/search?num=100&source=hp&q=3".$keyword."'>"
}
$FullContent = str_replace($arr_src, $arr_rpl, $FullContent)