PHP正则表达式获取字符串的一部分?

时间:2018-02-24 16:08:23

标签: php string

考虑我们有一个字符串(这是MySQL错误消息)如下:

  

数据截断列#sam_office_balance'在第1行

现在我需要单引号中的部分:

  

Sam Office Balance

$errorMessage = "Data truncated for column 'sam_office_balance' at row 1";
// do smthing
echo $message; //  Should print "Sam Office Balance"

最好的方法是什么?

我的解决方案

private function sqlErrorMessage($message){

      //My SQL DataType Error
      $error_string_1 = "Data truncated for column '";
      $error_string_2 = "' at row";
      $pos_error_string_1 = strpos($message, $error_string_1);
      $pos_error_string_2 = strpos($message, $error_string_2);
      if(gettype($pos_error_string_1) != "boolean" && gettype($pos_error_string_2) != "boolean"){
          $pos_error_string_1 += strlen($error_string_1);
          $errorColumn = substr($message, $pos_error_string_1, $pos_error_string_2 - $pos_error_string_1);
          $errorMessage = $this->uc_w($errorColumn)." has invalid data.";
          return $errorMessage;
      }

      return $message;
    }
  

语言:PHP

     

技术 使用最少代码行的任何内容。

2 个答案:

答案 0 :(得分:1)

您可以使用strposstrrpos函数查找'的第一个和最后一个出现的位置。

$string = "Data truncated for column 'sam_office_balance' at row 1";
$firstQuotePos = strpos($string, "'");
$lastQuotePos = strrpos($string, "'");
$column = substr($string, $firstQuotePos + 1, $lastQuotePos - $firstQuotePos - 1);

echo $column;

此代码将输出:

sam_office_balance

然后,您可以将_替换为str_replace函数),并将第一个字母设为大写(ucwords函数)。

echo ucwords(str_replace('_', ' ', $column));

以上代码将返回给您:

Sam Office Balance

如果你想拥有最大的短代码,你可以写:

echo ucwords(str_replace('_', ' ', substr($string, strpos($string, "'") + 1, strrpos($string, "'") - strpos($string, "'") - 1)));

答案 1 :(得分:1)

$errorMessage = "Data truncated for column 'sam_office_balance' at row 1";
$pattern = "/'([^']+)'/";
$error = preg_match($pattern, $errorMessage, $matches);
echo($matches[1]);