0

I have this string:

An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:

The string itself actually goes on and on for about another ~1000 characters. What I want to do is extract what's between Details: and \n\Stack. I'd end up with The Status you have chosen is invalid.

I think I have the preceding character removal using substr:

<?php
$error = "An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:.........";
$error2 = substr($error, 63);
echo $error2;
?>

But I always get an error syntax error, unexpected end of file. I figured out that it's the \n and \n\ that are throwing that error, but I have no control over those as they are returned to my script from an external API call. I've only defined the $error here for illustrative purposes. This error is present even if I just echo $error not just $error2.

I've seen that I can do something like $short = substr($str, 0, strpos( $str, ' - Name:')); for the trailing character removal, but I need to get the preceding working before I can do that.

Any advice appreciated!

Edit: I mentioned this in a comment, but the error string gets passed to my script from the API by $error = $e->getMessage();.

Ross
  • 173
  • 1
  • 2
  • 12
  • possible duplicate of [Get substring between two strings PHP](http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php) – Rizier123 Jan 09 '15 at 03:45
  • If echoing the first string produces `\n`, you should wrap your `$error` test string in single quotes, to prevent the `\n` from being parsed into a newline character. – Alexander O'Mara Jan 09 '15 at 03:46
  • So in the actual working file, the error comes from `$error = $e->getMessage();` so I can't really wrap it in quotes since it doesn't originate written out like that. I could be wrong though. – Ross Jan 09 '15 at 03:49
  • @HoboSapiens No joy. `PHP Parse error: syntax error, unexpected '^'` Ran it as `$errora = preg_match("/^.*\sDetails:\s(.*)\sStack/m", $error);` (Edit: Saw your edit, same error) – Ross Jan 09 '15 at 03:59
  • `preg_match` is indeed what you want. Use http://www.regexr.com/ to figure out the exact regular expression to use with it. Also: don't put the regex in double quotes. – Ben Overmyer Jan 09 '15 at 04:09

1 Answers1

1

Use a regex with the m and s modifiers so that you can match newlines:

<?php
$error = "An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:.........";

$result = preg_match("/^.*Details:\s(.*?)\n*Stack/ms", $error, $matches);
$errora = $matches[1];
echo $errora;
?>