Question

I'm parsing email subjects for specific information. The function below will return whatever string exists between 2 strings.

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

Resulting with: 6588 This is exactly what I wanted, of course. I just barely noticed that if I change the variables like this:

<?php
$string = 'New Ticket Email Submitted';
$begin = '[Ticket #';
$end = ']';
echo find_string_between_characters($string, $begin, $end); // result: t Email
?>

Resulting with: t Email

How do I adjust the function to look at the exact sequence of characters inside both the $begin and $end variables?

Was it helpful?

Solution

You can use preg_match as

$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])

OTHER TIPS

$string = 'Re: [Ticket #6588] Site security update';
preg_match('/\[Ticket #(.*?)\]/', $string, $matches);
print_r($matches);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top