php - 我想在一段中找到一个单词的第一个字母的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
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));
返回:
Array (
[firstWordofFirstLetterPosition] => 0
[firstWordofLastLetterPosition] => 2
)
推荐阅读
- sonarqube - 如果 sonar lint 与 sonarQube 集成,那么将从 SonarQube 获取规则?
- excel - Excel 2013(32 位)VBA Scripting.FileSystemObject.DIR 未列出所有文件
- mysql - 加快两个数据库之间的连接
- java - 将 SmbFile 从一个远程网络共享复制到另一个远程网络共享
- reactjs - React 路由器 V5 可选路径
- json - jq:解析错误:第 1 行第 14 列的数字文字无效
- sql - 从同一表 SQL Server 中的日期列更新月份列
- javascript - 如何在动画后将元素移回原点
- javascript - 期望字符串(用于内置组件)或类/函数(用于复合组件)但未定义
- python - 为什么在使用 pandas 读取 csv 时会自动删除前面的引号?