問題描述
是否有一些函數可以只從變量的引號中獲取文本?
就像:
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 echo
ing 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.
這篇關于獲取引號中的文本的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!