1
votes

Texte spécifique en gras dans une variable avec PHP?

J'essaye de modifier une chaîne dans mon projet. La chaîne que je modifie contient un paragraphe que l'utilisateur entre, et j'essaie de remplacer des occurrences spécifiques de mots (comme NOM / VERBE), par les noms et les verbes saisis par l'utilisateur. Tout fonctionne parfaitement, sauf que j'essaie de faire en sorte que la police des noms et des verbes saisis par l'utilisateur soit en gras, mais je ne peux pas savoir où mettre le texte en gras. Toutes les suggestions ou pointeurs seraient grandement appréciés.

<?php

//Variables
$stringFirstVerb = $_POST["stringFirstVerb"];             
$stringSecondVerb = $_POST["stringSecondVerb"];           
$stringThirdVerb = $_POST["stringThirdVerb"];             
$stringFirstNoun = $_POST["stringFirstNoun"];        
$stringSecondNoun = $_POST["stringSecondNoun"];             
$stringThirdNoun = $_POST["stringThirdNoun"];            
$stringFirstAdj = $_POST["stringFirstAdj"];     
$stringSecondAdj = $_POST["stringSecondAdj"];           
$stringThirdAdj = $_POST["stringThirdAdj"];             
$stringParagraph = $_POST["stringParagraph"];        
$intNounCount = 0;
$intVerbCount= 0;
$intAdjCount = 0;

//check for user input
$stringNewStr = implode("",array($stringFirstVerb,$stringSecondVerb,$stringThirdVerb,$stringFirstNoun,$stringSecondNoun,$stringThirdNoun,$stringFirstAdj,$stringSecondAdj,$stringThirdAdj));   //consolidates every replacable word into a single string

if( strpos($stringNewStr, ' ' ) !== false ){
echo "No spaces allowed in any Verbs, Nouns, or Adj's";
echo "<br>";
echo "<a href='project1.html'>Link to previous Page</a>";
}


else if( strpos($stringNewStr, '!' ) !== false  || strpos($stringNewStr, '.' ) !== false ||
strpos($stringNewStr, ';' ) !== false || 
strpos($stringNewStr, ':' ) !== false ||
strpos($stringNewStr, ',' ) !== false){
echo "No punctuation allowed in any Verbs, Nouns, or Adj's";
echo "<br>";
echo "<a href='project1.html'>Link to previous Page</a>";
}




else                    //if input is valid, moves onto next step

//checkif paragraph contains 3 of each word types
{

$stringNoun = "NOUN";
$intNounCount = (substr_count($stringParagraph, $stringNoun));

$stringVerb = "VERB";
$intVerbCount = (substr_count($stringParagraph, $stringVerb));

$stringAdj = "ADJ";
$intAdjCount = (substr_count($stringParagraph, $stringAdj));

echo $intNounCount;
echo $intAdjCount;
echo $intVerbCount;

if ($intNounCount !== 3 || $intVerbCount !== 3 || $intAdjCount !== 3){
echo "the paragraph must contain the words VERB, NOUN, and ADJ three times each!";
echo "<br>";
echo "<a href='project1.html'>Link to 
previous Page</a>";
}

else    //if conditions are met
{

//replace user entered words
$stringParagraph = str_replace('VERB1', 
$stringFirstVerb, $stringParagraph);    
//replaces the first verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('VERB2', 
$stringSecondVerb, $stringParagraph);     
//replaces the second verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('VERB3', 
$stringThirdVerb, $stringParagraph);     
//replaces the third verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('NOUN1', 
$stringFirstNoun, $stringParagraph);     
//replaces the first verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('NOUN2', 
$stringSecondNoun, $stringParagraph);     
//replaces the second verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('NOUN3', 
$stringThirdNoun, $stringParagraph);     
//replaces the third verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('ADJ1', 
$stringFirstAdj, $stringParagraph);     
//replaces the first verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('ADJ2', 
$stringSecondAdj, $stringParagraph);     
//replaces the second verb in the paragraph with user entered verb in bold text
$stringParagraph = str_replace('ADJ3', 
$stringThirdAdj, $stringParagraph);     
//replaces the third verb in the paragraph with user entered verb in bold text

echo $stringParagraph;          //outputs modified paragraph

echo "<br><br><br>";
echo "<a href='project1.html'>Enter another Madlibs!</a>";      //button to html page


//write paragraph to a txt file
$results = "results.txt";
//$resultsLink = fopen($results, 'a');
$stringFileParagraph = $stringParagraph;
//fwrite($resultsLink, 
$stringFileParagraph);
//fclose($resultsLink);

file_put_contents($results, 
$stringFileParagraph, FILE_APPEND); 
//saves the contents to a textfile, if textfile exists new entry will be added




}//end second else

}//end first else






?>

J'ai tenté de modifier les chaînes à l'intérieur de $ stringParagraph avec la commande str_replace mais je n'ai pas réussi. En bref, tout ce que j'essaye de faire est d'afficher le contenu de $ stringParagraph à l'utilisateur, le contenu de $ stringFirstNoun / SecondNoun étant en gras.


0 commentaires

3 Réponses :


-1
votes

Lorsque vous remplacez vos jetons, tels que VERB1 par les valeurs correspondantes, vous souhaitez placer cette valeur dans des balises en gras. Donc:

$stringParagraph = str_replace('VERB1', 
"<b>".$stringFirstVerb."</b>", $stringParagraph);

Doit être:

$stringParagraph = str_replace('VERB1', 
$stringFirstVerb, $stringParagraph);


1 commentaires

Remarque: selon la spécification HTML 5, la balise doit être utilisée comme dernier recours lorsqu'aucune autre balise n'est plus appropriée. La spécification HTML 5 stipule que les en-têtes doivent être désignés par les balises

à
, le texte mis en valeur par la balise , le texte important doit être indiqué par la balise et le texte marqué / mis en surbrillance doit utiliser la balise . w3schools.com/tags/tag_b.asp



0
votes
$stringParagraph = str_replace('VERB2', 
'<span class="highlight">' . $stringSecondVerb . '</span>', $stringParagraph);
Then the highlight class can style the replacements with whatever CSS you want, making it easy to change in the futureAlso you it's probably worth doing some sanitising on your variables, else you might as well have just used the post array directly.  As you're not doing any database work with this code your main risk is someone trying to embed a hidden script, you should take a look at strip_tags, or a preg_replace to clean out unwanted/potentially dangerous tags.And just as a thought, could you instead of having a long list of variables build a key => value array, then you could loop through the array ( or even better write a function) to replace your strings which would make it more easily expandable should you add in extra inputs (e.g verb4).  Unless you're using these variables somewhere outside of the code dislayed here?

2 commentaires

J'ai appliqué le code à mes lignes et elles n'ont pas été affectées. J'examinerai davantage la classe span pour voir si je peux faire fonctionner cela. Merci pour votre suggestion. Mise à jour: le code fonctionne très bien, merci beaucoup pour votre aide!


Soyons clairs, le span est une balise html et la classe est pour CSS, je travaille sur l'hypothèse que vous savez comment utiliser les classes CSS et CSS, etc. - la classe de surbrillance est un nom arbitraire pour l'exemple et ne le sera pas faire quoi que ce soit automatiquement. si ce n'est pas le cas, dites-le et je mettrai à jour la réponse



-1
votes

Je ne comprends vraiment pas vraiment votre question? Peut-être voulez-vous faire une action si l'utilisateur entre un nom / verbe en minuscules, l'action se déroule bien, mais si l'utilisateur entre un nom / verbe avec l'une des lettres saisies par l'utilisateur, l'action en majuscules échoue ??

Vous peut utiliser la fonction strtolower () , avant de combiner toutes les variables./

essayez ceci:

$stringNewStr = implode ("", array ($ stringFirstVerb, $ stringSecondVerb, $stringThirdVerb, $ stringFirstNoun, $ stringSecondNoun, $ stringThirdNoun, $stringFirstAdj, $ stringSecondAdj, $ stringSecondAdj, $ stringThirdAdj));

$stringNewStrLow = strtolower($stringNewStr);


1 commentaires

Vos variables ne sont pas valides, il ne peut pas y avoir d'espace entre $ et le nom de la variable. Aussi, veuillez utiliser le plus récent raccourci [] pour les tableaux à la place de array () .