dtnat7146 2019-03-21 13:27
浏览 118
已采纳

从位置替换字符串中的数组

I get trouble on replacing the word into special characters

First, I read the txt file and store each line into $line and put the special character that I want to change into $table array.

How do I change $line with special character $table array one by one based on the position for example, the txt include three words:

pads
password 
qwerty

so the program should show

p@ds
p@d$
p@ssword
p@$sword
p@$$word
p@$$w0rd
qwerty

Now my work just change all special characters into a new word. but how to change it using foreach / for loop one by one based on the position My code as follows

 <?php

    $file = fopen("text.txt", "r"); 
    while(!feof($file)) {
    $line = fgets($file);  
    $line = rtrim ($line);    

    $table = array(
        'a'=>'@', 'o'=>'0', 's'=>'$',   
    );


    $length = strlen($line);
    for ($i=0 ; $i<$length ; $i++){ 
        $line = strtr ($line, $table);
        echo $line."<br>";
    };
    }
    fclose($file);
?>
  • 写回答

2条回答 默认 最新

  • dqwolwst50489 2019-03-21 14:03
    关注

    This should do the job (haven't tested it):

    $char_array = str_split($line);
    $replaced = FALSE;
    foreach($char_array as $char) {
        if(array_key_exists($char, $table)) {
            $line = str_replace($char, $table[$char], $line, 1);
            echo $line."<br>";
            $replaced = TRUE;
        }
    }
    if(!$replaced)
        echo $line."<br>";
    

    By setting the count argument of str_replace to 1, you make sure only the current character is replaced and not all of them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失