[PHP] Hàm strpos trong PHP

ID Topic: 39127 • Có 82 lượt xem
Hình đại diện của thành viên
Ubuntu (Off) ♀️
Cấp độ: ☀️1/30☀️ ♡3♡
Like: 0/0
Online: ✨5/5364✨
????? ⚡??/??⚡
🩸3/4139🩸 🌟0/1310🌟
#1 - @620915
01/12/2024 01:27
1. Định nghĩa
- Hàm strpos() trong PHP dùng để tìm vị trí xuất hiện đầu tiên của một chuỗi con trong chuỗi cha

2. Cú pháp
Mã:strpos(string $haystack, string $needle, int $offset = 0): int|false

3. Tham số
- $haystack : chuỗi ký tự cha
- $needle : chuỗi ký tự con cần tìm kiếm
- $offset : tham số tùy chọn. Chỉ định vị trí bắt đầu tìm kiếm. Nếu $offset là số âm, vị trí tìm kiếm sẽ bắt đầu từ cuối chuỗi đảo ngược

4. Kết quả trả về
- false : Trả về false nếu không tìm thấy chuỗi con
- int : Trả về vị trí int xuất hiện đầu tiên của chuỗi con

5. Ví dụ:
- Ví dụ 1:
+ input:
Mã:<?php
$str 
= 'abcdefghimk';
$pos = strpos($str, 'd');
echo $pos;
?>

+ output:
Mã:3

- Ví dụ 2:
+ input:
Mã:<?php
$str 
= 'abcdefghdiklm';
$pos = strpos($str, 'd');
$pos2 = strpos($str, 'd', 5);
echo $pos . "\n";
echo $pos2;
?>

+ output:
Mã:3
8


- Ví dụ 3:
+ input:
Mã:<?php
$str 
= 'abcdefghdiklm';
$char = 'dk';
$pos = strpos($str, $char);
if ($pos == false) {
    echo "kí tự '" .$char. "' không tồn tại trong chuỗi";
}
?>

+ output:
Mã:kí tự 'dk' không tồn tại trong chuỗi

- Example #1 Using ===
+ input:
Mã:<?php
$mystring 
= 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
}
 else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

+ output:
Mã:The string 'a' was found in the string 'abc' and exists at position 0

- Example #2 Using !==
+ input:
Mã:<?php
$mystring 
= 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
}
 else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

+ output:
Mã:The string 'a' was found in the string 'abc' and exists at position 0

- Example #3 Using an offset
+ input:
Mã:<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
echo $pos;
?>

+ output:
Mã:7

6. Tài liệu tham khảo
https://www.php.net/manual/en/function.strpos.php
(Google Chrome Browser)
PM | Trích dẫn | Like bài viết | Sửa | Xóa | Báo cáo | Cảnh cáo
Trả lời nhanh

Chủ đề tương tự