我正在解析电子邮件主题以获取特定信息。 下面的函数将返回2个字符串之间存在的任何字符串。
<?php
function find_string_between_characters($haystack, $starter, $ender) {
if(empty($haystack)) return '';
$il = strpos($haystack,$starter,0)+strlen($starter);
$ir = strpos($haystack,$ender,$il);
return substr($haystack,$il,($ir-$il));
}
$string = 'Re: [Ticket #6588] Site security update';
$begin = '[Ticket #';
$end = ']';
echo find_string_between_characters($string, $begin, $end); // result: 6588
?>
结果: 6588 当然,这正是我想要的。 我几乎没有注意到,如果我改变这样的变量:
<?php
$string = 'New Ticket Email Submitted';
$begin = '[Ticket #';
$end = ']';
echo find_string_between_characters($string, $begin, $end); // result: t Email
?>
结果: t电子邮件
如何调整功能以查看 $ begin 和 $ end 变量中的确切字符序列?
答案 0 :(得分:1)
$string = 'Re: [Ticket #6588] Site security update';
preg_match('/\[Ticket #(.*?)\]/', $string, $matches);
print_r($matches);
答案 1 :(得分:1)
您可以将preg_match用作
$input_line = 'Re: [Ticket #6588] Site security update' ;
preg_match("/\[Ticket #(.*?)\]/i", $input_line, $output_array);
echo $output_array[1];
/\[Ticket #(.*?)\]/i
\[ matches the character [ literally
Ticket # matches the characters Ticket # literally (case insensitive)
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\] matches the character ] literally
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])