|
编写一个简单的函数进行测试
- function findFirstLineContainingKeyword($post, $keyword) {
- $lines = explode("\n", $post);
- foreach ($lines as $line) {
- if (strpos($line, $keyword) !== false) {
- return $line;
- }
- }
- return null; // Keyword not found
- }
复制代码
此代码首先使用 explode("\n", $post) 将 $post 字符串按行拆分为一个数组。然后,它遍历每一行并使用 strpos($line, $keyword) !== false 检查 $keyword 是否存在。如果找到,该函数将返回该行。如果没有,则返回 null 。
使用示例:
- $post = "This is a multi-line string.\nI'm searching for the keyword 'keyword'.\nHere it is: keyword found!";
- $keyword = "keyword";
- $firstLine = findFirstLineContainingKeyword($post, $keyword);
- if ($firstLine) {
- echo "The first line containing the keyword is: " . $firstLine;
- } else {
- echo "Keyword not found.";
- }
复制代码 |
|