简体   繁体   English

PHP RegEx 删除特定字符之间的字符

[英]PHP RegEx remove characters between specific characters

I've done some digging around and can't seem to find an exact answer to this question.我已经做了一些挖掘,似乎无法找到这个问题的确切答案。 I've tried online regex testers to no avail.我试过在线正则表达式测试器无济于事。 I am trying to remove text from a string between 2 points.我正在尝试从 2 点之间的字符串中删除文本。

Here is an example of the string:这是字符串的示例:

##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago

I would like to trim the string to say only Awesome service .我想修剪字符串只说Awesome service

So, I need to remove the ## and everything in between, as well as Message-ID through sprut .所以,我需要通过sprut删除##和中间的所有内容,以及Message-ID

How can I achieve this?我怎样才能做到这一点?

EDIT: Just to be clear, i am trying to squeeze this into a php expression.编辑:为了清楚起见,我试图将其压缩到一个 php 表达式中。 This is what i have that is not working:这是我所拥有的,但不起作用:

<?php 

if(preg_match('##(.*?)##\\s*(.+?)\\s*Message-Id:.*$',$tweet['tweet'],$matches)) $tweet['tweet'] = $matches[1];
echo (string) trim($tweet["tweet"]);

?>

You can easily match portion between ## and ## using ##(.*?)## .您可以使用##(.*?)##轻松匹配####之间的部分。 Also removing everything after message id is trivial: Message-Id:.* .在 message id 之后删除所有内容也很简单: Message-Id:.* Joined together you have: ~##(.*?)##\\\\s*(.+?)\\\\s*Message-Id:.*$~ and you can easily use one of these:连接在一起你有: ~##(.*?)##\\\\s*(.+?)\\\\s*Message-Id:.*$~并且你可以很容易地使用以下之一:

$regex = '~##(.*?)##\\s*(.+?)\\s*Message-Id:.*$~';

// Use replace
$data = preg_replace( $regex, '$2', $data);

// Or match
$matches = array();
if( preg_match($regex, $data, $matches)){
    $data = $matches[2];
}

Life example here .生活例子在这里

preg_match("!## (.+) Message.+ - (.+)!", $your_text, $taken)

访问捕获的单词,如果它们是 'isset' $taken[1] 和 $taken[2]

You can use:您可以使用:

$re = "/##.*?## *| Message-Id:.*$/"; 
$str = "##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago"; 

$result = preg_replace($re, '', $str); // Awesome service

Working Demo工作演示

You could use a positive lookaheads and lookbehinds to extract the string Awesome Service which was in between ## and Message-ID .您可以使用正向前瞻和后视来提取位于##Message-ID之间的字符串Awesome Service

<?php
$mystring = "##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago";
$regex = '~.*(?<=##\s)(.*)(?= Message-Id:).*~';
$replacement = "$1";
echo preg_replace($regex, $replacement, $mystring);
?> //=> Awesome service

Working DEMO工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM