首页 > 解决方案 > 我想在一段中找到一个单词的第一个字母的strpos

问题描述

在段落中查找单词的第一个字母strpos()。我尝试获取段落中单词的所有首字母..

$paragraph = "A pangram or holoalphabetic win sentence is a sentence that contains every knight letter of the alphabet at least once.  
              The most famous pangram is probably the thirty-five-letter-long The quick brown fox jumps over the lazy dog,  
              which has been used to test typing equipment since at least the late Pangrams are an important tool for 
              testing typing equipment and compactly showing off every letter of price related etc";

$array = range('a','z');

// to find the first letter of each word in the paragraph 

$words = explode(" ", $paragraph);
$letters = "";
foreach ($words as $value) {
    $letters .= substr($value, 0, 1);
}

$countLetters = strtolower($letters);

==================================================== =====================

如果我将“p”作为选定的字母表,那么我想找到它的第一个和最后一个单词的字符串位置..

段落中的第一个单词 p = "pangram" --> 找到 p 的 strpos ...

段落中的最后一个单词 p = "price" --> find strpos of p ...

前任..

output = {
            "p":{
                    "firstWordofFirstLetterPosition":2,
                    "firstWordofLastLetterPosition":"strpos of p in price"
                }

标签: php

解决方案


这是你想要的吗?支持多字节字符串:

<?php

function firstWordsInParagraph(string $input, string $letter) {
    $lowercaseLetter = mb_strtolower($letter);

    // return only words having given letter
    $words = array_filter(explode(' ', $input), function ($word) use ($lowercaseLetter) {
        return mb_strpos(mb_strtolower($word), $lowercaseLetter) !== false;
    });

    // no matches found!
    if (empty($words)) {
        return [
            'firstWordofFirstLetterPosition' => null,
            'firstWordofLastLetterPosition' => null,
        ];
    }

    return [
        'firstWordofFirstLetterPosition' => mb_strpos(current($words), $lowercaseLetter),
        'firstWordofLastLetterPosition' => mb_strpos(end($words), $lowercaseLetter),
    ];
}

$input = 'kolorowa żółć w żniw pożodze';
$letter = 'ż';

print_r(firstWordsInParagraph($input, $letter));

例如:https ://3v4l.org/7Go7i

返回:

Array (
   [firstWordofFirstLetterPosition] => 0
   [firstWordofLastLetterPosition] => 2
)

推荐阅读