次の配列について考えてみます。
$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}
言い換えると、会社名のすべてのインスタンスを、「リンゴは素敵な果物」というスペースで囲まれている場合、文字列の最初が「リンゴは素晴らしい」の後のスペースにある場合、または文字列の最後にある場合に置き換えたいと考えています。先頭に「これが私のリンゴです」
これにはおそらく正規表現が必要ですが、それを書くのに助けが必要です。