获取引号中的文本

2021-12-22 00:00:00 text php quotes

是否有一些函数可以只从变量的引号中获取文本?
就像:

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.

相关文章