获取引号中的文字 [英] Get text in quotes

查看:151
本文介绍了获取引号中的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些函数可以仅将文本放在变量引号内?
就像:

is there is some function that can take just text inside the quotes from the variable?
Just like:

$text = 'I am "pro"';
echo just_text_in_quotes($text);

我知道此功能不存在..但是我需要类似的东西. 我在想fnmatch("*",$text) 但这无法回显仅此文本,仅用于检查. 你能帮我么? 谢谢.

I know that this function doesn't exist.. but I need something like that. I was thinking about fnmatch("*",$text) But this cant Echo just that text, It's just for check. Can you please help me? Thank you.

推荐答案

此函数将返回引号之间的第一个匹配文本(可能为空字符串).

This function will return the first matched text between quotes (possibly an empty string).

function just_text_in_quotes($str) {
   preg_match('/"(.*?)"/', $str, $matches);
   return isset($matches[1]) ? $matches[1] : FALSE;
}

您可以修改它以返回所有匹配项的数组,但是在您的示例中,您可以在echo返回其值的上下文中使用它.如果它返回一个数组,您将得到的只是Array.

You could modify it to return an array of all matches, but in your example you use it within the context of echoing its returned value. Had it returned an array, all you would get is Array.

编写更好的通用函数(可以处理多次出现)和自定义定界符可能会更好.

You may be better off writing a more generic function that can handle multiple occurrences and a custom delimiter.

function get_delimited($str, $delimiter='"') {
    $escapedDelimiter = preg_quote($delimiter, '/');
    if (preg_match_all('/' . $escapedDelimiter . '(.*?)' . $escapedDelimiter . '/s', $str, $matches)) {
        return $matches[1];
    }
}

如果未找到匹配项,则返回null.

This will return null if no matches were found.

这篇关于获取引号中的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆