0

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?

3
  • 1
    a simple preg_match() would be easy Commented Apr 14, 2014 at 21:21
  • is the patter is constant i.e. [Ticket #6588] ? Commented Apr 14, 2014 at 21:21
  • Yep, luckily pretty constant. Commented Apr 14, 2014 at 21:23

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

Comments

1
$string = 'Re: [Ticket #6588] Site security update';
preg_match('/\[Ticket #(.*?)\]/', $string, $matches);
print_r($matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.