PHP 正则表达式标题转换/负向前瞻/toLowerCase
我正在尝试将 html 页面中的一些标题转换为
。图案很简单。
<?php
$test = "<p><strong>THIS IS A TEST</strong></p><div>And this is Random STUFF</div><p><strong>CP</strong></p>";
$pattern = "/<p><strong>([A-Z ]*?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test = preg_replace($pattern, $replacement, $test);
?>
基本上,抓取
之间大写的任何内容。很简单,所以这里是复杂的部分。
首先,我需要破例。 CP
不得转换为
。我尝试在
之后添加
?!(CP)
但它不起作用。
其次,我需要能够将第一个字母大写。当我在 preg_replace 上使用“ucfirst”和“strtolower”时(例如:ucfirst(strtolower(preg_replace($pattern, $replacement, $test)));
),它会生成字符串转换为小写,ucfirst 不起作用,因为它正在检测“<”成为第一个角色。
有什么提示或者我是否朝着正确的方向前进?
编辑
感谢您的帮助,使用 preg_replace_callback
绝对更好。我发现我所有的标题都超过 3 个字符,所以我添加了限制器。还添加了特殊字符。 这是我的最终代码:
$pattern = "/<p><strong>([A-ZÀ-ÿ0-9 ']{3,}?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test[$i] = preg_replace_callback($pattern, create_function('$matches', 'return "<h2>".ucfirst(mb_strtolower($matches[1]))."</h2>";'), $test[$i]);
I'm trying to convert some titles in my html pages to <h2>
. The pattern is simple.
<?php
$test = "<p><strong>THIS IS A TEST</strong></p><div>And this is Random STUFF</div><p><strong>CP</strong></p>";
$pattern = "/<p><strong>([A-Z ]*?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test = preg_replace($pattern, $replacement, $test);
?>
Basically, grab anything that's between <p><strong></strong></p>
that is capitalized. Easy enough, so here's the complicated bit.
Firstly, I need to make a single exception. <p><strong>CP</strong></p>
must not be converted to <h2>
. I tried adding ?!(CP)
right after the <p><strong>
but it doesn't work.
Secondly, I need to be able to make the first letter capitalized. When I use "ucfirst" with "strtolower" on the preg_replace (ex:ucfirst(strtolower(preg_replace($pattern, $replacement, $test)));
), it makes all the characters in the string to lowercase and ucfirst doesn't work as it's detecting "<" to be the first character.
Any hints or am I even going in the right direction?
EDIT
Thanks for the help, it was definitely better to use preg_replace_callback
. I found that all my titles were more than 3 characters so I added the limiter. Also added special characters.
Here's my final code:
$pattern = "/<p><strong>([A-ZÀ-ÿ0-9 ']{3,}?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test[$i] = preg_replace_callback($pattern, create_function('$matches', 'return "<h2>".ucfirst(mb_strtolower($matches[1]))."</h2>";'), $test[$i]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试 http://php.net/manual/de/function.preg-替换回调.php 。
您可以创建一个在每场比赛中调用的自定义函数。在此函数中,您可以决定 a) 不替换 CP,b) 不放入 $1,而是放入 ucfirst。
希望这有帮助&祝你好运。
Try http://php.net/manual/de/function.preg-replace-callback.php .
You can create a custom function that is called on every match. In this function you can decide to a) not replace CP and b) to not put $1, but ucfirst.
Hope this helps & good luck.