PHP :: Aufgabe #79
5 Lösungen

Palindrom erkannt, Gefahr gebannt...
Anfänger - PHP
von ElPapito
- 08.05.2015 um 19:53 Uhr
Ein Palindrom ist ein Wort, welches von vorn wie von hinten gelesen werden kann (z.B. Anna, Lagerregal, ...).
Schreibe ein Programm, welches ein Wort einliest und prüft ob dieses ein Palindrom ist.
Klein- und Großschreibung wird hierbei vernachlässigt, d.h. 'A' == 'a', 'B' == 'b', usw.
Beispiele:
Eingabe: Lagerregal
Palindrom
Eingabe: Wasserfall
Kein Palindrom
Schreibe ein Programm, welches ein Wort einliest und prüft ob dieses ein Palindrom ist.
Klein- und Großschreibung wird hierbei vernachlässigt, d.h. 'A' == 'a', 'B' == 'b', usw.
Beispiele:
Eingabe: Lagerregal
Palindrom
Eingabe: Wasserfall
Kein Palindrom
Lösungen:

<?php $ergebnis = 'Bitte geben Sie erst ein Wort ein.'; if(isset($_POST['submit'])) { $wort = $_POST['wort']; $no_reverse =strtolower($wort); $reverse = strtolower(strrev($wort)); if($no_reverse == $reverse) { $ergebnis = <<<EOF <span style="font-weight:bold"> {$wort} </span> ist ein Palindrom.<br /> EOF; } else { $ergebnis = <<<EOF <span style="color:red"> {$wort} </span> ist kein Palindrom.<br /> EOF; } } echo <<<EOF <p> Ist das ein Palindrom?</p> <form action="palindrom.php" method="post"> <label>Wort:</label> <input type="text" name="wort"><br/><br /> <input type="submit" name="submit" value="senden"> </form> <p>Ergebnis: {$ergebnis}</p> EOF; ?>

<?php function pruefen($wort) { $palindrom = strrev($wort); if (strtolower($palindrom) === strtolower($wort)) { echo 'Eingabe: ' . $wort . '<br />Palindrom'; }else { echo 'Eingabe: ' . $wort . '<br />Kein Palindrom'; } } if(isset($_POST['submit'])) { if(strpos($_POST['palindrom'], ' ') === false && !is_numeric($_POST['palindrom'])) { pruefen($_POST['palindrom']); }else { echo 'Bitte gebe nur ein Wort ein.'; } } ?>

<html> <form action="palindrom.php" method="POST"> Bitte ein Wort eingeben: <input type="text" name="palindrom"><br /> <input type="submit" name="submit" value="Prüfen"> </form> </html>

<?php function IsPalindrom($input) { return (strtoupper($input) == strtoupper(strrev($input))) ? "ein Palindrom<br />" : "kein Palindrom<br />"; } echo "Anna ist " . IsPalindrom("Anna"); echo "Bier ist " . IsPalindrom("Bier"); ?>

<?php //beliebige Eingabe machen $eingabe = 'Wasserfall'; echo $eingabe; $erg = palindrom($eingabe); echo '<br/>'.$erg; function palindrom($wort) { $wort = strtolower($wort); $umgekehrt = strrev($wort); if($umgekehrt == $wort) { return "Das Wort ist ein Palindrom!"; } else { return "Kein Palindrom!"; } } ?>

function palindrom($input){ $arrOld = [str_split($input)]; $arrNew = []; $length = count($arrOld[0]); for ($i = 0; $i < $length; $i++){ array_push($arrNew, end($arrOld[0])); array_pop($arrOld[0]); } $newString = implode($arrNew); if (strtolower($newString) == strtolower($input)){ echo $input . " ist ein Palindrom"; }else{ echo $input . " ist kein Palindrom"; } }
Konsolenausgabe:
"Deine Eingabe" ist ein Palindrom