根据PHP中输入的字符操作单个字符串

时间:2013-04-24 19:35:59

标签: php arrays string character

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

2 个答案:

答案 0 :(得分:1)

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

查看preg_match

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

$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

答案 1 :(得分: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;