从 PHP 字符串中去除字符
Strip Characters from PHP String
我有这个字符串:
An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:
字符串本身实际上持续了约 1000 个字符。我想做的是提取 Details:
和 \n\Stack
之间的内容。我最终会得到 The Status you have chosen is invalid.
我想我使用 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;
?>
但我总是得到一个错误 syntax error, unexpected end of file
。我发现是 \n
和 \n\
引发了该错误,但我无法控制它们,因为它们是从外部 API 调用返回到我的脚本的。我在这里定义 $error
只是为了说明目的。即使我只是回显 $error
而不仅仅是 $error2
.
也会出现此错误
我已经看到我可以执行 $short = substr($str, 0, strpos( $str, ' - Name:'));
之类的操作来删除尾随字符,但我需要先完成前面的工作才能执行此操作。
感谢任何建议!
编辑: 我在评论中提到了这一点,但错误字符串通过 $error = $e->getMessage();
.[=15 从 API 传递到我的脚本=]
使用带有 m
和 s
修饰符的正则表达式,以便您可以匹配换行符:
<?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;
?>
我有这个字符串:
An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:
字符串本身实际上持续了约 1000 个字符。我想做的是提取 Details:
和 \n\Stack
之间的内容。我最终会得到 The Status you have chosen is invalid.
我想我使用 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;
?>
但我总是得到一个错误 syntax error, unexpected end of file
。我发现是 \n
和 \n\
引发了该错误,但我无法控制它们,因为它们是从外部 API 调用返回到我的脚本的。我在这里定义 $error
只是为了说明目的。即使我只是回显 $error
而不仅仅是 $error2
.
我已经看到我可以执行 $short = substr($str, 0, strpos( $str, ' - Name:'));
之类的操作来删除尾随字符,但我需要先完成前面的工作才能执行此操作。
感谢任何建议!
编辑: 我在评论中提到了这一点,但错误字符串通过 $error = $e->getMessage();
.[=15 从 API 传递到我的脚本=]
使用带有 m
和 s
修饰符的正则表达式,以便您可以匹配换行符:
<?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;
?>