让我们说我们有这4个字符串:
string1 = "Hello my name is 'George' and im fine";
string2 = "Hello my name is 'Mary' and im fine";
string3 = "Hello my name is 'Peter' and im fime";
string4 = "Hello my name is 'Kate' and im fine";
我们如何才能只提取包含''?
中名称的字符串部分提前致谢!
答案 0 :(得分:2)
你应该使用正则表达式:
preg_match("/'(.+?)'/", $string, $matches);
print_r($matches);
详情请见http://php.net/preg_match和http://lt.php.net/preg_match_all
答案 1 :(得分:1)
$pieces = explode("'", $string);
echo $pieces[1];
答案 2 :(得分:0)
在特定情况下,您可以使用explode函数将字符串拆分为基于分隔符的数组,撇号将用于分隔字符串,以便以下代码可以产生您的答案:
$tokens= explode("'", "Hello my name is 'Kate' and im fine");
//The value you require is now found in $tokens[1];
echo $tockens[1];
或者,您可以使用preg_match将常规表达式匹配存储在常规表达式中的特定组中:
$pattern = "Hello my name is '(.*)' and im fine";
preg_match ($pattern , "Hello my name is 'Kate' and im fine", $matches)
//The value you require is now found in $matches[1];
echo $matches[1];
答案 3 :(得分:0)
$string1 = "Hello my name is 'George' and im fine";
preg_match_all("/\'(.*)\'/",$string1,$matches,PREG_SET_ORDER);
echo $matches[0][1];
上面将匹配单引号之间任意长度的字符串。如果您希望将单个单词与单引号匹配' \ w +'代替'。'也会这样做。