0

我想知道如何在 PHP 中操作字符串中的单个字符。我已经搜索了所有内容,找不到任何可以回答此类问题的内容。我想获取一个使用输入表单提交的字符串,例如,“这是一个句子”,然后创建一个输出,该输出获取每个单词的第一个字符并将其放在该单词的末尾:“hist si一个句子”。我假设第一步是获取字符串并使用explode()将其转换为数组,但我真的很困惑如何执行实际操作?这里的任何帮助都会很棒!谢谢!

4

2 回答 2

1

您应该考虑preg_match使用正则表达式: http: //php.net/manual/en/function.preg-match.php

然后,您可以将匹配项存储到数组中并操作字符串。

$string = "this is a sentence";

$regex = '/<insert regex here>/'; // Regex expert edit here please  

preg_match($regex, $string, $matches)
// Uses regex against string and stores matches
// into $matches <-- that is optional but in your case you want to use it for manipulation

var_dump($matches); // Play with results
于 2013-04-24T19:38:46.317 回答
1

我知道正则表达式应该是要走的路,但我只是觉得这很有趣,所以这里是:

    $string = "this is a sentence";
    $stringArray = explode(" ", $string);

    $messedSentence = "";
    foreach($stringArray as $word)
    {
        $word = trim($word);
        $firstChar = substr($word,0,1);
        $lastChar = substr($word,strlen($word)-1,1);
        $restOfWord = substr($word,1,strlen($word)-2);

        if(trim($word)) 
        {
            $messedSentence .= (strlen($word)==1)?$firstChar." ":$lastChar.$restOfWord.$firstChar. " ";
        }
    }

    echo $string ." becomes: ".$messedSentence;
于 2013-04-24T20:10:55.577 回答