php - 如何正确使用rtrim函数在PHP中删除字符串末尾的字符
问题描述
我有一个重力表单,它接受用户的输入,然后根据输入创建一封通知电子邮件。
在后端,我有通知设置来构建一个 html 电子邮件。它从复选框的选择中生成 H2 标签。
H2 最终看起来像这样: 需要兽医助理:渐进式实践,最好的客户,在工作中学习,!
我想删除这个 H2 末尾的逗号和感叹号。
这是我的代码:
function alter_ad( $notification, $form, $entry ) {
//grab the message portion of the notification
$data = $notification['message'];
//find the h2 header in the notification
preg_match('/<h2>(.*?)<\/h2>/s', $data, $match);
//store the content h2 in variable
$header = $match[1];
//trim off the exclamation point
$new_header = rtrim($header, '!');
//now trim off the comma at the end
$new_header_two = rtrim($new_header, ',');
//now header should have the comma and exclamation at the end removed
//so now I need to find the h2 in the message again and replace its contents with the new
header text
$start = '<h2>';
$end = '</h2>';
$result = replace_content_inside_delimiters($start, $end, $new_header_two, $data);
$notification['message'] = $result;
return $notification;
}
function replace_content_inside_delimiters($start, $end, $new, $source) {
return preg_replace('#('.preg_quote($start).')(.*?)('.preg_quote($end).')#si',
'$1'.$new.'$3', $source);
}
add_filter( 'gform_notification_42', 'alter_ad', 10, 3 );
但是,当我提交通知时,它删除了感叹号,但结尾的逗号仍然存在。我对第二个 rtrim() 做错了吗?
通知中的 h2 标头在运行过滤器后最终看起来像这样:
需要兽医助理:渐进式实践,最好的客户,在工作中学习,
解决方案
好吧,您在这种情况下提供的字符串有感叹号,!
然后是空格
,然后是逗号,
。
所以
//trim off the exclamation point
$header= rtrim($header, "!");
//now trim off the space
$header= rtrim($header, " ");
//now trim off the comma at the end
$header= rtrim($header, ",");
或在一行中:
$header = rtrim($header, "! ,");
请参阅此处的代码示例:http: //codepad.org/PNqjFL8h
推荐阅读
- python - Chi2 不具备任何功能
- raspberry-pi - 通过 rclone 将 RaspberryPi 目录与 OneDrive 同步
- json - 将示例数据转换为真实的 json 数据
- ruby-on-rails - 以编程方式检测 Rails (zeitwerk) 类卸载
- c# - Xamarin IOS - 从库或相机中挑选视频并在 CollectionViewCell 中显示
- python - 如何使用日期作为 pandas pivot_table 中的值而不是数字数据?
- node.js - 我可以在我的 package.json 中编写一种重定向导出来弥补我的一个部门中缺少的导出吗?
- automated-tests - Appium Pagefactory 从 POM 运行时抛出 noSuchMethodException
- wordpress - 自定义类型 - 显示所有分类名称和图像
- javascript - 什么是:{名称:“泰勒”}在javascript中?