欢迎访问宙启技术站
智能推送

实用的PHP函数示例代码

发布时间:2023-07-06 02:59:12

1. 获取当前时间戳

$timestamp = time();
echo $timestamp;

2. 格式化时间戳为日期

$timestamp = time();
$date = date('Y-m-d H:i:s', $timestamp);
echo $date;

3. 获取当前页面的URL

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;

4. 判断一个字符串是否包含另一个字符串

$haystack = "This is a sample string";
$needle = "sample";
if (strpos($haystack, $needle) !== false) {
    echo "The string contains the word 'sample'";
} else {
    echo "The string does not contain the word 'sample'";
}

5. 判断一个字符串是否以某个子字符串结尾

$string = "This is a sample string";
$ending = "string";
if (substr($string, -strlen($ending)) === $ending) {
    echo "The string ends with 'string'";
} else {
    echo "The string does not end with 'string'";
}

6. 发送电子邮件

$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}

7. 使用正则表达式匹配字符串

$string = "This is a sample string";
$pattern = "/\b(sample)\b/";
if (preg_match($pattern, $string)) {
    echo "The string matches the pattern";
} else {
    echo "The string does not match the pattern";
}

8. 对字符串进行加密和解密

$string = "This is a sample string";
$encrypted = base64_encode($string);
echo "Encrypted string: " . $encrypted . "
";
$decrypted = base64_decode($encrypted);
echo "Decrypted string: " . $decrypted;

9. 将数组转换为JSON格式的字符串

$array = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($array);
echo $json;

10. 将JSON格式的字符串转换为数组

$json = '{"name":"John","age":30,"city":"New York"}';
$array = json_decode($json, true);
print_r($array);