Consider the following array:
$companies = array(
'apple' => 'AAPL',
'baxter' => 'BAX'
);
And the following strings:
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
I’m using the following loop to replace company names with their respective ticker:
foreach ($companies as $name => $ticker) {
$tweet = str_replace(" $name", "<b>{COMPANY|$ticker}</b>", $tweet);
}
This results in
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}
However, I would also like to cath company names at the beginning of a string:
{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}
But if I remove the space in " $name", words like bapple will also be replaced:
{COMPANY|AAPL} at the beginning of string with b{COMPANY|AAPL}
In other words: I want to replace all instances of company names
– when surrounded by spaces “an apple is lovely fruit”
– when at the beginning of string with a space after “apple is wonderfull”
– or when at the end of a string with leading space “so this is my apple”
This would probably require a regex, but I would need some help in writing it.
Try this:
The regex uses so-called word boundaries: http://www.regular-expressions.info/wordboundaries.html
The output is now:
If you also want to support things like
apples, then take this code:}