考虑以下数组:
$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}
换句话说:我想替换公司名称的所有实例 - 当被空间包围时,"苹果是可爱的水果" - 当字符串的开头在"苹果很棒"之后有一个空格时 - 或者在带有前导空格的字符串末尾"所以这是我的苹果"
这可能需要正则表达式,但我在编写它时需要一些帮助。
我认为你需要的是带有单词边界的正则表达式b
http://www.regular-expressions.info/wordboundaries.html
我不是 php 开发人员,但您应该使用正则表达式:"b"+$name+"b"
.
这里的关键是:
- 确保在进入正则表达式
- 之前引用您的公司名称,因为如果您的公司名称包含正则表达式语法中表示某些内容的字符,您会遇到问题
- 使用单词边界(
b
)来标识"独立"的字符串 - 将您的公司名称包装在正则表达式的括号中,然后如果需要,您可以在替换中访问括号位
$1
请考虑以下示例:
$companies = array(
'apple' => 'AAPL',
'baxter' => 'BAX'
);
$input = "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 => $code)
{
$input = preg_replace(sprintf('/b(%s)b/i',preg_quote($name)),'{COMPANY:'.$code.'}',$input);
}
var_dump($input);
这将为您提供:
{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}
试试这个:
foreach ($companies as $name => $ticker) {
$tweet = preg_replace('/b'.preg_quote($name).'b/', "<b>{COMPANY|$ticker}</b>", $tweet);
}
正则表达式使用所谓的单词边界:http://www.regular-expressions.info/wordboundaries.html
输出现在为:
{公司|AAPL} 在字符串的开头,此处为 带有 {COMPANY| 的字符串AAPL} 在中间 {公司|BAX}{公司|BAX} 第一名和第二名 mybaxters 最后, {公司|BAX}
如果您还想支持类似 apples
,那么请采用以下代码:
foreach ($companies as $name => $ticker) {
$tweet = preg_replace('/b'.preg_quote($name).'s{0,1}b/', "<b>{COMPANY|$ticker}</b>", $tweet);
}
花了我一些时间,但后来你得到了一些东西
$companies = array(
'apple' => 'AAPL',
'baxter' => 'BAX'
);
$str = '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 $search => $company)
{
$regex = '!(?<=b|^)('.$search.')(?=b|$)!ui';
$str = preg_replace($regex, $company, $str);
}
echo $str;