开发者

while-loops and if-statement trouble php

开发者 https://www.devze.com 2023-02-15 21:55 出处:网络
I want to be able to check wheter an inputted string has any of the characters in $alphabet and if it does display the relevant image per relevant character. so if someone entered hello. it would disp

I want to be able to check wheter an inputted string has any of the characters in $alphabet and if it does display the relevant image per relevant character. so if someone entered hello. it would display h.png, e.png, l.png, l.png and o.png. So far I have got it to recognise the users input and echo it out and search whether it has a par开发者_JAVA技巧ticular letter and output it to the relevant image via this code:

<?php
$input = trim($_POST["textarea"]);

echo $input;
echo "<br />";

if(strcmp($input[0],'a')==0){
    echo "<img src='egypt/$input.png'>";
    }else{
    echo "You did not write a";
    }


?>

Which works perfectly. However I tried to input more code which would allow a whole string including spaces to be analysed against the whole alphabet $alphabet and match each character in the string to the right image with this code below: but it doesnt work

<?php
    $input = trim($_POST["textarea"]);

    echo $input;
    echo "<br />";


    $alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');


    while (list(, $value) = each($alphabet) AND list(, $input) = each($value2)) {  
    if(strcmp($value2[0],$value)==0){
        echo "<img src='egypt/$value2.png'>";
        }else{
        echo "You did not write a";
        }
    }


    ?>

Above is the neccessary code.

Update: I have worked out how to match the first letter of input against any in the alphabet but still struggling to work out how to map against a whole string with spaces.

<?php
$input = trim($_POST["textarea"]);

echo $input;
echo "<br />";

$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');


  if(strcmp($input[0],$alphabet)==0){
    echo "<img src='egypt/$input.png'>";
    }else{
    echo "Error";
    }


?>

Code with reference to update for anyone who cares


Let me suggest you a different route.

$fos='hello world!';
$cucc=preg_replace('/([a-z])/', '<img src="$1.png" />', $fos);

This will replace every letter (a-z) with its img equivalent, so you will get this result:

<img src="h.png" /><img src="e.png" /><img src="l.png" /><img src="l.png" /><img src="o.png" /> <img src="w.png" /><img src="o.png" /><img src="r.png" /><img src="l.png" /><img src="d.png" />!


I'm not sure if this will solve your problem completely, but I noticed this right away:

while (list(, $value) = each($alphabet) AND list(, $input) = each($value2))

should be:

while (list(, $value) = each($alphabet) AND list(, $value2) = each($input))

0

精彩评论

暂无评论...
验证码 换一张
取 消