簡體   English   中英

如何找到字符串位置的PHP

[英]How to find string position php

我想在$ string中的每個單詞中獲得'ja'的位置,但是它不起作用。 我究竟做錯了什么?

<?php
$offset = 0;

$find = 'ja';
$find_length = strlen($find);

$string = 'jasim jasmin jassir';

while ($string_position = strpos($string, $find, $offer)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
  1. 將變量名稱更改為$offset
  2. strpos可能返回0, while將其視為false

因此,將您的while語句替換為:

while (($string_position = strpos($string, $find, $offset)) !== false) {

嘗試改變目標

<?php
$offset = 1;

$find = 'ja';
$find_length = strlen($find);

$string = 'jasim jasmin jassir';

while ($string_position = strpos($string, $find, $offset)) {
echo $find.' found at '.$string_position.'<br>';
$offset = $string_position + $find_length;
}
?>
// output :- ja found at 6
             ja found at 13

如果您不想更改膠印使用

$string = ' jasim jasmin jassir'; (without space not be jasim it's 'jasim )

然后它將輸出3

    ja found at 1
ja found at 7
ja found at 14

嘗試更改條件檢查

while (($string_position = strpos($string, $find, $offset)) !== false) {
<?php
            // stack overflow area

            $offset = 0;

            $find = 'ja';
            $find_length = strlen($find);

            $string = 'jasim jasmin jassir';
            if (strpos($string, $find) === false) {
                echo "not found";
            }
            else {
                while (strpos($string, $find, $offset) !== false) {
                    $string_position = strpos($string, $find, $offset);
                    echo $find.' found at '.$string_position.'<br>';
                    $offset = $string_position + $find_length;
                }
            }
?>

很少有解決方法,但顯然可以。

輸出:

ja找到於0

ja發現於6

ja發現於13

可能您應該以這種方式編碼以找到字符串位置

$positions = array();
$offset = -1;
while (($pos = strpos($string, $find, $offset+1)) !== false) {
    $positions[] = $offset;
}

$result = implode(', ', $positions);

打印此結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM