Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP从字符串中拆分类名_Php_Regex_String_Variables - Fatal编程技术网

PHP从字符串中拆分类名

PHP从字符串中拆分类名,php,regex,string,variables,Php,Regex,String,Variables,您好,我有一个变量($variable1)包含以下字符串: $variable1 = class="our-products type-our-products status-publish format-standard has-post-thumbnail hentry product-status-previous-product" 我只想获取字符串的最后一个类部分(此类名更改为3个选项中的1个): 产品状态以前的产品 产品状态当前产品 产品状态未来产品 检索列表中最后一个类名的最佳和最

您好,我有一个变量(
$variable1
)包含以下字符串:

$variable1 = class="our-products type-our-products status-publish format-standard has-post-thumbnail hentry product-status-previous-product"
我只想获取字符串的最后一个类部分(此类名更改为3个选项中的1个):

  • 产品状态以前的产品
  • 产品状态当前产品
  • 产品状态未来产品

  • 检索列表中最后一个类名的最佳和最有效的PHP命令是什么?然后我将使用switch语句根据最后一个类名进行操作。

    首先,您的语法无效,我假设您将整个变量保存为字符串,如下所示:

    $variable1 = "class=our-products type-our-products status-publish format-standard has-post-thumbnail hentry product-status-previous-product";
    
    $pattern = '/(\w+\-\w+\-\w+\-\w+)\s*$/';
    preg_match($pattern, $variable1, $matches);
    print_r($matches);
    
    $variable1 = 'class="our-products type-our-products status-publish format-standard has-post-thumbnail hentry product-status-previous-product"';
    
    您可以编写一个简单的函数,从该模式中获取所有类作为数组,然后使用以下方法返回最后一个类:

    然后可以调用变量上的函数以获取最后一个类:

    try {
        echo "The last class is: " . getLastClass($variable1);
    } catch (InvalidArgumentException $e) {
        // Something went wrong...
        echo $e->getMessage();
    }
    

    用空格爆炸,得到最后一个元素。这很完美,我不需要全部使用。我将变量的格式更改为数组,并使用了end方法,它成功了。谢谢请添加一些解释性文字,而不是添加普通代码。普通代码可能很难理解,并且在这样发布时可能会吸引反对票。
    try {
        echo "The last class is: " . getLastClass($variable1);
    } catch (InvalidArgumentException $e) {
        // Something went wrong...
        echo $e->getMessage();
    }