问题描述
是否有比以下更大胆的方法来检查最后一个字符是“s”还是“z”:
if (substr($var,-1,1) == "s" OR substr($var,1) == "z") ...
类似的东西
if (substr($var,1) == "s" OR "z") ...
会很好,但 PHP 中有这样的东西吗?
解决方法
使用 in_array
并查找数组中的最后一个字符:
if (in_array(substr($var,-1,1),['s','z']))
,
或者:
in_array(array_pop(explode('',$var)),'z'])` ?
不是更可读也不是英勇,但我知道什么? :)
,厌倦了太容易理解的代码?正则表达式来拯救:
<?php
$service_url = 'https://********/PostRequest';
$curl = curl_init($service_url);
//collection Object
$data = array(
'request' => array(
"Key1" => "*****","key2" => "","key3" => "****","key4" => "****","key5" => "****","key6" => "****","key7" => "***","key8" => "****","key9" => "***","key10" => "****","key11" => "***","ItemList" => array(
"subkey1" => "***","subkey2" => "***","subkey3" => "****","subkey4" => "****","subkey5" => "****","subkey6" => "*****","subkey7" => "***","subkey8" => "***","subkey9" => "***","subkey10" => "**","Subkey11" => "**","subkey12" => "**","subkey13" => "04","subkey14" => "010101","Subkey15" => "R","Subkey16" => "70","Subkey17" => array(
"string" => "00"
)
),"Address" => array(
"PrimaryAddressLine" => "","SecondaryAddressLine" => "","County" => "","City" => "","State" => "","PostalCode" => "****","Plus4" => "","Country" => "","Geocode" => "","VerifyAddress" => "false"
),)
);
$data_json = json_encode($data);
// Set the CURLOPT_RETURNTRANSFER option to true
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl,CURLOPT_POST,true);
// Set custom headers for RapidAPI Auth and Content-Type header
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_json);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
die();
,
如果您能够使用 PHP8,那么您应该可以在 PHP8 中使用这个简单的解决方案。
https://www.php.net/manual/en/function.str-ends-with.php
<?php
$text = 'foods';
if (str_ends_with($text,'s') || str_ends_with($text,'z')) { ... }