使用PHP提取特定字符串

使用PHP提取特定字符串,php,string,extract,Php,String,Extract,假设我们有以下4个字符串: string1=“你好,我叫‘乔治’,我很好” string2=“你好,我叫‘玛丽’,我很好” string3=“你好,我叫‘彼得’,我是菲姆” string4=“你好,我叫‘凯特’,我很好” 如何仅提取包含“”中名称的字符串部分 提前谢谢 您可能应该使用正则表达式: $pieces = explode("'", $string); echo $pieces[1]; preg_match("/'(.+?)'/", $string, $matches); print_

假设我们有以下4个字符串:

  • string1=“你好,我叫‘乔治’,我很好”
  • string2=“你好,我叫‘玛丽’,我很好”
  • string3=“你好,我叫‘彼得’,我是菲姆”
  • string4=“你好,我叫‘凯特’,我很好”
  • 如何仅提取包含“”中名称的字符串部分


    提前谢谢

    您可能应该使用正则表达式:

    $pieces = explode("'", $string);
    echo $pieces[1];
    
    preg_match("/'(.+?)'/", $string, $matches);
    print_r($matches);
    

    有关和的详细信息,请参见。您可能应该使用正则表达式:

    preg_match("/'(.+?)'/", $string, $matches);
    print_r($matches);
    

    有关和的详细信息,请参见。您可以使用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_匹配来存储正则表达式中针对特定组的正则表达式匹配:

    $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];
    

    您可以使用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_匹配来存储正则表达式中针对特定组的正则表达式匹配:

    $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];
    
    上面将匹配单引号之间任意长度的字符串。如果要将单个单词与单引号匹配,也可以使用“\w+”代替“.*”


    上面将匹配单引号之间任意长度的字符串。如果您希望用单引号匹配单个单词,也可以用“\w+”代替“*”。

    我认为您需要转义单引号。我认为您需要转义单引号。我有:$string1=“我的名字是‘Kate’,我很好”;$pattern=“我的名字是'(.*),我很好”;预匹配($pattern,$string1,$matches);//您需要的值现在可以在$matches[1]中找到;但它返回以下错误:警告:preg_match()[function.preg match]:分隔符不能是字母数字或反斜杠echo$matches[1];我有:$string1=“我的名字是‘凯特’,我很好”;$pattern=“我的名字是'(.*),我很好”;预匹配($pattern,$string1,$matches);//您需要的值现在可以在$matches[1]中找到;但它返回以下错误:警告:preg_match()[function.preg match]:分隔符不能是字母数字或反斜杠echo$matches[1];