如何在字符串中间的开头,结尾或(作为一个单词)替换公司名称?

时间:2012-04-24 16:20:29

标签: php regex

考虑以下数组:

$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}

但是,我还希望在字符串的开头使用cath公司名称:

{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}

换句话说:我想替换公司名称的所有实例   - 当被空间包围时“苹果是可爱的水果”   - 在“apple is wonderfull”之后的字符串开头处有空格   - 或者在带有前导空格的字符串末尾“这是我的苹果”

这可能需要一个正则表达式,但我需要一些帮助来编写它。

5 个答案:

答案 0 :(得分:2)

我认为您需要的是带有字边界\b

的正则表达式

http://www.regular-expressions.info/wordboundaries.html

答案 1 :(得分:2)

我不是php开发人员,但您应该使用正则表达式:"\b"+$name+"\b"

答案 2 :(得分:2)

这里的关键是:

  • 确保在进入正则表达式之前引用您的公司名称,因为如果您的公司名称包含表示正则表达式语法的字符,您将遇到问题
  • 使用字词边界(\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}

答案 3 :(得分:1)

试试这个:

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


输出现在是:

  

{COMPANY | AAPL} 在字符串的开头用bapple这里a   中间带 {COMPANY | AAPL} 的字符串 {COMPANY | BAX}    {COMPANY | BAX} 在第一和第二位mybaxters,最后,    {COMPANY | BAX}

如果您还想支持apples之类的内容,请使用以下代码:

foreach ($companies as $name => $ticker) {
  $tweet = preg_replace('/\b'.preg_quote($name).'s{0,1}\b/', "<b>{COMPANY|$ticker}</b>", $tweet);

}

答案 4 :(得分:1)

花了我一些时间,但后来你得到了一些东西

$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;