Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用正则表达式替换文本,同时去除换行符和引号_Php_Regex_Preg Replace_Pcre - Fatal编程技术网

Php 使用正则表达式替换文本,同时去除换行符和引号

Php 使用正则表达式替换文本,同时去除换行符和引号,php,regex,preg-replace,pcre,Php,Regex,Preg Replace,Pcre,这现在主要是学术性的,因为我可以通过其他方式获得相同的结果,但是…这一直困扰着我,我相信使用regex是可能的 我想使用PHP的preg_replace来替换内容,因此: Content: “String <tag>This is some content, which contains newlines and quotation marks.</tag> and other unrelated content”. Regex: /<tag>(.*)<

这现在主要是学术性的,因为我可以通过其他方式获得相同的结果,但是…这一直困扰着我,我相信使用regex是可能的

我想使用PHP的preg_replace来替换内容,因此:

Content: “String <tag>This is some content, which contains newlines and quotation marks.</tag> and other unrelated content”.

Regex: /<tag>(.*)<\/tag>/sU

Replace: “String of other content, including matched pattern $1”
Content:“String这是一些内容,包含换行符和引号。以及其他不相关的内容”。
正则表达式:/(.*)/sU
替换:“其他内容的字符串,包括匹配的模式$1”

但是问题是,我想去掉元素之间的任何换行符和/或引号。什么正则表达式允许我这样做?

PHPs preg_replace()对主题进行一次性处理。实际上,您可以指定一个模式和替换数组,但是在主题字符串的每个部分上只有一个匹配。使用单正则表达式肯定没有解决方案,因为这个问题不在常规语言中。理论计算机科学告诉我们,你需要一个有状态的自动机来完成这样的任务。正则表达式是原始的

正如arkascha指出的,这并不是一个很容易一次解决的问题

可以在Perl中一步完成:

use strict;
use warnings;
my $string = "blah <tag> foo \"bar \n </tag> baz";

$string =~ s/(?<=\<tag\>)([^<]+)(?=\<\/tag\>)/$_=$1;s|[\n\"]||gs;$_/ges;

print $string;
使用严格;
使用警告;
my$string=“blah foo\”bar\n baz”;

$string=~s/(?不容易,但可能

尝试以下PHP代码

function myFn($a, $b, $c) {
  $b = preg_replace("!(?:\\\'|[\"\n\r])!", '', $b);
  return "BEGIN " . $b . " END";
}
$s = "abc <tag>def \n ghi 'jkl' mno \"pqr\" stu</tag> vwx";
$s = preg_replace('!(<tag>)(.*?)(</tag>)!ise', 'myFn("$1", "$2", "$3")', $s);
print $s;

测试这段代码。

也许这会让你走上正确的方向:而且,关于这一点,有很多话题。那么:你尝试了什么,或者你试图实现什么?也许你正在尝试使用一个regex,其中构建了一个特定的php函数。是的,很明显,regex本身并不是解决方案,但问题是我很感兴趣,所以我想知道这是否可能。换言之,这是可能的,但不是一个人应该做的事情……寻求替代解决方案;)
abc BEGIN def  ghi jkl mno pqr stu END vwx