大佬教程收集整理的这篇文章主要介绍了如何检查设置在php字符串中的被调用字符串?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找调用多个字符串并将它们连接成一个字符串.我希望能够检查所有被调用的字符串是否都已设置,而不必使用isset();.每个使用的字符串.
我理想地希望拥有:
@H_403_6@<?PHP
$name = "John Smith";
$age = "106";
$favAnimal = "pig";
$email = "john@smith.com";
$sport = "tennis";
$userDescription = "My name is $name, I am $age years old, I like $sport.";
if(allStringsSet($userDescription)){
echo $userDescription; //Or do something else
}
?>
您会注意到,我没有调用所有字符串,因为在我的应用程序中,并非所有字符串都会一直使用.我的应用程序还将从大约50个字符串中进行选择,而我需要能够检查是否有任何setset,而不会到处都是isset(); s.
我希望在声明$userDescription之前需要进行isset检查.如何检查一组未知的字符串以查看是否已设置?
解决方法:
使用带有自定义getter和setter的对象.
@H_403_6@class CustomStrings()
{
protected $data;
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
if (isset($data[$key])) {
return $data[$key];
}
return false;
}
public function getDescription($description) {
// regex to find the words following : (or any other char)
// look for the variables, and do whatever handling you want if they're not found
// return whatever you want
// IF you don't want to do a regex, you can do the following
foreach ($this->data as $key => $value) {
$description = str_replace(":$key", $value, $description);
}
if (strpos(':', $description) !== falSE) {
return $description;
}
return false; // or whatever error handling you want
}
}
$Strings = new CustomStrings();
$Strings->name = 'John';
$Strings->age = 16;
$Strings->sport = 'Football';
$description = $Strings->getDescription("My name is :name, I am :age years old, I like :sport");
您将使用适当的键将所有变量存储在CustomStrings对象中,而不是写入$name,而是写入:name.
您只能在getDescription函数中执行一次isset处理.
因为我很懒,所以我没有写正则表达式.如果要在字符串中使用:,请将其替换为不需要的内容.
祝好运!
以上是大佬教程为你收集整理的如何检查设置在php字符串中的被调用字符串?全部内容,希望文章能够帮你解决如何检查设置在php字符串中的被调用字符串?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。