考虑以下数组:
$companies = array(
'apple' => 'AAPL',
'baxter' => 'BAX'
);
以及以下字符串:
apple at the beginning of string with bapple
here a string with apple in the middle
baxter baxter on first and second place mybaxters
and finally, baxter
我正在使用以下循环将公司名称替换为各自的股票代码:
foreach ($companies as $name => $ticker) {
$tweet = str_replace(" $name", "<b>{COMPANY|$ticker}</b>", $tweet);
}
这导致
apple at the beginning of string with bapple
here a string with {COMPANY|AAPL} in the middle
baxter {COMPANY|BAX} on first and second place mybaxters
and finally, {COMPANY|BAX}
但是,我还想在字符串的开头加上公司名称:
{COMPANY|AAPL} at the beginning of string with bapple
here a string with {COMPANY|AAPL} in the middle
{COMPANY|BAX} {COMPANY|BAX} on first and second place mybaxters
and finally, {COMPANY|BAX}
但如果我删除 中的空格" $name"
,类似的单词bapple
也会被替换:
{COMPANY|AAPL} at the beginning of string with b{COMPANY|AAPL}
换句话说:我想替换公司名称的所有实例 - 当被空格包围时“一个苹果是可爱的水果” - 当在字符串的开头时,在“苹果是美妙的”之后有一个空格 - 或者当在字符串的结尾时带前导空格“所以这是我的苹果”
这可能需要一个正则表达式,但我需要一些帮助来编写它。