如何在字符串的第一行末尾附加一个字符?

时间:2019-11-14 01:18:24

标签: php

基本上,我只是想在一个字符串的第一行末尾添加一个冒号,该字符串用于表示python中的一个小函数。我已经处理了确定冒号是否在第一行末尾的逻辑,因此鉴于此,我将如何在第一行的末尾添加冒号?这是字符串的样子。

<?php
    $input = "def sum(numbers)
    total = 0
    for x in numbers:
        total += x
    return total
print(sum((8, 2, 3, 0, 7)))";

    $firstline = strstr($input,"\n",true);  //retrieve first line

    print($firstline);  //print first line, just for testing
?>

我在w3schools和东西上浏览了几个函数,找到了strstr()函数,但这仅选择第一行。

我想到的一个粗略(我认为)解决方案可能是像使用strstr()一样检索第一行,然后在不包含第一行的情况下获取字符串的其余部分,然后在我之后将它们重新连接在一起分别编辑第一行。这会是最好的方法吗?

有什么方法可以选择性地仅在PHP中编辑字符串的第一行吗?

2 个答案:

答案 0 :(得分:1)

使用*.cproj,我们可以捕获第一行,然后替换为最后添加的冒号。

preg_replace

此打印:

$input = "def sum(numbers)
total = 0
for x in numbers:
    total += x
return total
print(sum((8, 2, 3, 0, 7)))";

$output = preg_replace("/^(.*?)\n/", "$1:\n", $input);
echo $output;

答案 1 :(得分:1)

有许多PHP函数可以帮助您实现:http://php.net/substr_replacehttp://php.net/substrhttp://php.net/str_replace

<?php
    $input = "def sum(numbers)
    total = 0
    for x in numbers:
        total += x
    return total
print(sum((8, 2, 3, 0, 7)))";

    $firstline = strstr($input,"\n",true);  //retrieve first line
    $colon =':';
    $newinput= str_replace($firstline, $firstline.$colon, $input);

    print($newinput); 
?>