php 如何使用正则表达式提取php中的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5588615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract text in php using regex
提问by faressoft
My Text :
我的文字:
12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/plain; charset="iso-8859-6" Content-Transfer-Encoding: base64 DQrn0Ocg0dPH5MkgyszR6sjqySDl5iDH5OfoyuXq5A0KDQrH5OTaySDH5NnRyOrJIOXP2ejlySAx MDAlDQogCQkgCSAgIAkJICA= --_12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/html; charset="iso-8859-6" Content-Transfer-Encoding: base64 PGh0bWw+DQo8aGVhZD4NCjxzdHlsZT48IS0tDQouaG1tZXNzYWdlIFANCnsNCm1hcmdpbjowcHg7
I want to extract iso-8859-6
我要提取iso-8859-6
回答by Billy Moon
you could do: preg_match('/charset="([^"]+)"/',$string,$m); echo $m[1];
你可以这样做: preg_match('/charset="([^"]+)"/',$string,$m); echo $m[1];
Edit: In case all need matching (prompted from other answer) modify like this:
编辑:如果所有需要匹配(从其他答案提示)修改如下:
preg_match_all('/charset="([^"]+)"/',$string,$m); print_r($m);
preg_match_all('/charset="([^"]+)"/',$string,$m); print_r($m);
回答by zx81
The regex you are looking for is:
您正在寻找的正则表达式是:
iso[^"]+
The php code you need is:
您需要的php代码是:
<?php
$subject='12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/plain; charset="iso-8859-6" Content-Transfer-Encoding: base64 DQrn0Ocg0dPH5MkgyszR6sjqySDl5iDH5OfoyuXq5A0KDQrH5OTaySDH5NnRyOrJIOXP2ejlySAx MDAlDQogCQkgCSAgIAkJICA= --_12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/html; charset="iso-8859-6" Content-Transfer-Encoding: base64 PGh0bWw+DQo8aGVhZD4NCjxzdHlsZT48IS0tDQouaG1tZXNzYWdlIFANCnsNCm1hcmdpbjowcHg7';
$pattern='/iso[^"]+/m';
if (preg_match($pattern, $subject, $match))
echo $match[0];
?>
The output is:
输出是:
iso-8859-6
回答by Jim Wolff
if you are interested in getting both matches (since you have 2 in the string) and iterate through them you should do something like this. also i used single quotes to not have to escape the quotes inside the regex. used ridgerunners suggestions aswell.
如果您有兴趣获得两个匹配项(因为字符串中有 2 个)并遍历它们,您应该执行类似的操作。我也使用单引号不必转义正则表达式中的引号。也使用了 ridgerunners 的建议。
preg_match_all('/charset="([^"]+)"/', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
# Matched text = $result[0][$i];
}