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

PHP函数:substr()的用法和示例

发布时间:2023-06-03 23:36:05

1、substr()函数的用法

substr()函数是用来截取一个字符串的一部分,并以字符串形式返回该部分。这个函数的语法格式如下:

string substr ( string $string , int $start [, int $length ] )

其中,string参数是要截取的字符串,$start参数是要开始截取的位置,$length参数是截取的长度,可以省略。如果省略$length参数,则会从$start位置一直截取到字符串的结尾。

2、substr()函数的示例

2.1、截取字符串的一部分

<?php

$str = "Hello World";

echo substr($str, 0, 5); // 输出 "Hello"

?>

以上示例中,substr()函数将从0位置开始截取$str字符串的前5个字符,并将结果输出。

2.2、截取字符串的末尾一部分

<?php

$str = "abcdefg";

echo substr($str, -3); // 输出 "efg"

?>

以上示例中,substr()函数将从字符串末尾开始往前数3个字符,并将结果输出。

2.3、省略$length参数

<?php

$str = "Hello World";

echo substr($str, 6); // 输出 "World"

?>

以上示例中,substr()函数将从第6个字符开始截取$str字符串到结尾的所有字符,并将结果输出。

2.4、截取日期的年份、月份和日份

<?php

$date = "2021-07-26";

$year = substr($date, 0, 4); // 截取年份

$month = substr($date, 5, 2); // 截取月份

$day = substr($date, 8, 2); // 截取日份

echo "年份:".$year.", 月份:".$month.", 日份:".$day; // 输出 "年份:2021, 月份:07, 日份:26"

?>

以上示例中,使用了substr()函数来截取日期字符串的年份、月份和日份,并将结果输出。

2.5、截取URL字符串中的主机名和路径

<?php

$url = "https://www.example.com/path/to/page.html";

$host = substr($url, 8, strpos($url, "/", 8) - 8); // 截取主机名

$path = substr($url, strpos($url, "/", 8)); // 截取路径

echo "主机名:".$host.", 路径:".$path; // 输出 "主机名:www.example.com, 路径:/path/to/page.html"

?>

以上示例中,使用了substr()函数和strpos()函数来截取URL字符串中的主机名和路径,并将结果输出。