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();
}