首页 > 解决方案 > 如何正确使用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 标头在运行过滤器后最终看起来像这样:

需要兽医助理:渐进式实践,最好的客户,在工作中学习,

标签: phpgravityforms

解决方案


好吧,您在这种情况下提供的字符串有感叹号,!然后是空格 ,然后是逗号,

所以

 //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


推荐阅读