首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式不会改变PHP中的任何文本

正则表达式不会改变PHP中的任何文本
EN

Stack Overflow用户
提问于 2013-07-08 19:41:42
回答 5查看 95关注 0票数 1

我有这样的代码来替换每一个数字(和点),并用<b>and the text</b>替换它

代码语言:javascript
复制
<?

function reem2($cadena) {

   $buscarRegex = array('/^([0-9]{1}|[.])$/i');
   $reemplazo = array('<b>$i</b>');
   $mag = preg_replace($buscarRegex, $reemplazo, $cadena);

   return $cadena;
}

$string = "1. Krewella - Can't Control Myself
2. Kdrew - Circles
3. Korn Feat. Skrillex & Kill The Noise - Narcissistic Cannibal
4. Netsky - Love Has Gone
5. Example - Midnight Run (Flux Pavilion Remix)
6. Madeon - Finale (Radio Version)
7. Feed Me Vs. Knife Party Vs. Skrillex - My Pink Reptile Party (Maluu's Slice'n'diced Mashup)
8. Krewella & Pegboard Nerds - This Is Not The End
9. Skrillex - Bangarang
10. The Prototypes - Suffocate
11. Ayah Marar - Mind Controller (Cutline Remix)
12. Skrillex Feat. Krewella - Breathe (Vocal Edit)
13. Utah Saints Vs. Drumsound & Bassline Smith - What Can You Do For Me (Tantrum Desire Remix)
14. Nero - Promises (Skrillex & Nero Remix)
15. 20 Florence & The Machine - Cosmic Love (Seven Lions Remix)";

echo reem2(nl2br($string));

?>

但它不起作用,也改变不了什么:

HTML中的输出是:

1. Krewella无法控制自己

2. Kdrew圈

3. Korn Feat.Skrillex &扑灭噪音-自恋食人族

4. Netsky -爱情已经消失

5.示例-午夜跑步(Flux )

6.制作总决赛(无线电版本)

7. Feed .刀党大战。Skrillex -我的粉色爬行动物党(Maluu's片‘n’Slice)

8. Krewella & Pegboard --这不是终点

9. Skrillex - Bangarang

10.原型-窒息

11. Ayah Marar - Mind Controller (割线Remix)

12. Skrillex壮举。Krewella -呼吸(声乐编辑)

13.犹他州圣徒队。鼓音和巴西史密斯-你能为我做些什么(愤怒的欲望,雷米克斯)

14. Nero承诺(Skrillex & Nero )

15. 20佛罗伦萨与机器-宇宙之爱(七只狮子雷米克斯)

我能做什么?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-07-08 19:48:33

您可以使用以下代码:

代码语言:javascript
复制
function reem2($cadena) {
   $buscarRegex = array('/^(\d+\.)/mi'); // This means match any digit(s) followed by a dot at the beginning of each line. Note the m modifier
   $reemplazo = array('<b>$1</b>'); // replace should be with group 1, not some vague $i
   $mag = preg_replace($buscarRegex, $reemplazo, $cadena);
   return $mag; // return value: fixed
}
票数 1
EN

Stack Overflow用户

发布于 2013-07-08 19:45:21

你的审判断了:

代码语言:javascript
复制
/^([0-9]{1}|[.])$/i
 ^-- start of line 
                ^--- end of line

您只允许一行上的一个字符本身,所以正则表达式永远不能匹配任何东西。

你可能想要更像这样的东西:

代码语言:javascript
复制
/^([\d]+)\./

它将匹配行开头的任意数量的数字,后面跟着一个.

票数 2
EN

Stack Overflow用户

发布于 2013-07-08 19:43:34

代码语言:javascript
复制
return $cadena;

是您的问题所在,您执行替换,然后丢弃结果并返回输入。

代码语言:javascript
复制
return $mag;

可能是你的意思

事实上,您的regex也是错误的。

代码语言:javascript
复制
function reem2($cadena) {

   $buscarRegex = array('/^([0-9]{1,2}\.)(.*)$/m');
   $reemplazo = array('<b>\1</b>\2');
   $mag = preg_replace($buscarRegex, $reemplazo, $cadena);

   return $mag;
}

似乎是你想要的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17534633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档