📜  php 包含子字符串 - PHP (1)

📅  最后修改于: 2023-12-03 14:45:22.698000             🧑  作者: Mango

PHP包含子字符串

在PHP中包含子字符串可以通过多种方式实现。以下是一些使用字符串函数和正则表达式的常见方法。

使用substr函数

substr函数可以从字符串中提取子字符串。

<?php

$str = "Hello World";
// 返回"World"
$subStr = substr($str, 6);

?>
使用strstr函数

strstr函数可以查找并返回一个字符串在另一个字符串中的第一次出现。

<?php

$str = "Hello World";
// 返回"World"
$subStr = strstr($str, "World");

?>
使用strpos函数

strpos函数可以查找并返回一个字符串在另一个字符串中的第一次出现的位置。

<?php

$str = "Hello World";
// 返回6
$subStrIndex = strpos($str, "World");

?>
使用preg_match函数

preg_match函数可以使用正则表达式查找并返回匹配的子字符串。

<?php

$str = "Hello World";
// 返回"World"
preg_match("/W\w+/", $str, $matches);
$subStr = $matches[0];

?>

以上是一些基本的PHP包含子字符串的方法。具体使用哪个方法取决于你的需求和个人偏好。