creating a find and replace application in php - php

i have a php code :
<?php
$offset=0;
if(isset($_POST['text']) && isset($_POST['searchfor']) && isset($_POST['replacewith']))
{
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$search_length=strlen($search);
if(!empty($text)&&!empty($search)&&!empty($replace))
{
while($strpos=strpos($text,$search,$offset))
{
$offset=$strpos + $search_length;
$text=substr_replace($text,$replace,$strpos,$search_length);
}
echo $text;
}
else
{
echo 'pls fill in all fields';
}
}
?>
<form action='string_search.php' method='POST'>
<textarea name='text' rows='6' cols='30'></textarea><br><br>
Search For:
<input type='text' name='searchfor'><br><br>
Replace with:
<input type='text' name='replacewith'><br><br>
<input type='submit' value='find and replace'>
</form>
When i type a string.Forexample 'i found my dog' in textarea and search for 'dog' in 'search for' then replace with 'cat' in 'replace' then submit it will out put 'i found my cat'.However it always output the original string ('i found my dog').I don't know why ?

Why do you use:
while($strpos=strpos($text,$search,$offset)) {
$offset=$strpos + $search_length;
$text=substr_replace($text,$replace,$strpos,$search_length);
}
echo $text;
??
I think its the same if you just use:
$strpos=strpos($text,$search);
$text=substr_replace($text,$replace,$strpos,$search_length);
echo $text;
And probably is your while who is doing the bad work. I don't know, it's a suggestion. With this, your code should work.

<?php
$offset = 0;
if (isset($_POST['user_input_box']) && isset($_POST['search']) && isset($_POST['replace'])) {
$user_input_box = $_POST['user_input_box'];
$search = $_POST['search'];
$replace =$_POST['replace'];
//To check whether above code work or not
// echo $user_input_box = $_POST['user_input_box'];
// echo $search = $_POST['search'];
// echo $replace = $_POST['replace'];
$search_length = strlen($search);
if (!empty($_POST['user_input_box']) && !empty($_POST['search']) && !empty($_POST['replace'])) {
while ($string_position=strpos($user_input_box, $search ,$offset)) {
// to check while and strpos
// echo $string_position."<br>";
// echo $offset = $string_position + $search_length;
$offset = $string_position + $search_length;
$user_input_box = substr_replace($user_input_box, $replace,$string_position,$search_length );
}
echo $user_input_box;
}
else{
echo "Please fill the complete fields.";
}
}
?>
<form method="POST" action="eleven0.php">
<textarea cols="34" rows="12" name="user_input_box"></textarea>
<br><br>
<label>Search For: </label> <br>
<input type="text" name="search"><br><br>
<label>Replace With: </label><br>
<input type="text" name="replace"><br><br>
<input type="submit" value="Find and Replace">
</form>

Related

while loop doesn't work properly,why?

It keeps (echo)ing sth.
<?php
$offset=0;
if (isset( $_POST['text']) && isset( $_POST['search_for']) && isset($_POST['replace'])){
$text= $_POST['text'];
$replace= $_POST['replace'];
$search= $_POST['search_for'];
$string_length=strlen($search);
if (!empty ($text) && !empty($search) && !empty($replace)){
while ($strpos=strpos($text,$search,$offset))
echo $strpos.'<br>';
echo $offset=$strpos+$string_length.'<br>';
} else {
echo 'please fill all fields';
}
}
?>
<form action='index.php' method ='POST'>
<textarea name='text' rows=6 cols=30 > </textarea><br><br>
Search for:<br>
<input type ='text' name='search_for'><br><br>
Replace with:<br>
<input type='text' name='replace'><br><br>
<input type='submit' value='Find & Replace'>
</form>
You forgot brackets around the while body:
if (!empty ($text) && !empty($search) && !empty($replace)) { // here
while ($strpos=strpos($text,$search,$offset)) {
echo $strpos.'<br>';
echo $offset=$strpos+$string_length.'<br>';
} // here
} else {
Without these brackets just first command is executed (echo $strpos) during the loop and after the loop the second echo is written.
Your code was the same as:
if (!empty ($text) && !empty($search) && !empty($replace)) { // here
while ($strpos=strpos($text,$search,$offset)) {
echo $strpos.'<br>';
} // here the while loop ends
echo $offset=$strpos+$string_length.'<br>';
} else {
You did a mistake { :
while ($strpos=strpos($text,$search,$offset)) {
So :
<?php
$offset=0;
if (isset( $_POST['text']) && isset( $_POST['search_for']) && isset($_POST['replace'])){
$text= $_POST['text'];
$replace= $_POST['replace'];
$search= $_POST['search_for'];
$string_length=strlen($search);
if (!empty ($text) && !empty($search) && !empty($replace)){
while ($strpos=strpos($text,$search,$offset)) { // You forgetten the {
echo $strpos.'<br>';
echo $offset=$strpos+$string_length.'<br>';
} else {
echo 'please fill all fields';
}
}
?>
<form action='index.php' method ='POST'>
<textarea name='text' rows=6 cols=30 > </textarea><br><br>
Search for:<br>
<input type ='text' name='search_for'><br><br>
Replace with:<br>
<input type='text' name='replace'><br><br>
<input type='submit' value='Find & Replace'>
</form>

I have the following string in a text file:

I have a code but is not working, I'm trying use explode but still not working.
My code have two strings:
^#^b = (on)
^A^b = (off)
I try to get only 2 characters from a .txt file in a variable like:
$on=^#
$off=^A
then I can use the result to verify the state of light using a dimmer.
Code
<?php
if(isset($_POST['estado'])) {
exec('/var/www/www.rfteste.com/htdocs/estado.sh');
}
if(isset($_POST['ligar'])) {
exec('/var/www/www.rfteste.com/htdocs/liga.sh');
}
if(isset($_POST['desligar'])) {
exec('/var/www/www.rfteste.com/htdocs/desliga.sh');
}
echo "<H3>CONTROL PANEL</H3>";
$str = file_get_contents("/var/www/www.rfteste.com/htdocs/estado.txt");
$vals = explode("^", $str);
$num1 = "^".$vals[0];
$num2 = "^".$vals[1];
$onoff= "^A";
if($num2 == $onoff)
echo "<b>on</b>";
else
echo "<b>off</b>";
?>
<html>
<body>
<form method="post" action="">
<p>
<center><input type="submit" value="Ligar" name="ligar""';" /></center>
<center><input type="submit" value="desligar" name="desligar""';" /></center>
<center><input type="submit" value="atualizar" name="estado""';" /></center>
i think this can help you solve your problem
function checktext($text){
if(preg_match("'#'", $text)){
return 'on';
}else{
return 'off';
}
}
echo checktext('^A^b');
Use php substr()
if(substr($str, 0, 1) == "A")
{
echo "<b>on</b>";
} else {
echo "<b>off</b>";
}

How to count input that have value?

in my code, when we click ok button . It's will echo 3
I want to apply to count only input that have value only
How to do ?
<?php
if(isset($_POST["submit"]))
{
echo count($_POST["to_more"]);
}
?>
<form name="f1" method="post">
<input type="text" name="to_more[]">
<input type="text" name="to_more[]">
<input type="text" name="to_more[]">
<input type="submit" name="submit" value="OK">
</form>
try this
<?php
if(isset($_POST["submit"]))
{
echo count(array_filter($_POST["to_more"]));
}
?>
How about
if(isset($_POST["submit"])){
$count = 0 ;
foreach($_POST["to_more"] as $data){
if($data != '') $count++;
}
if($count > 0)
echo $count;
}
array_filter should help
<?php
$ar = isset($_POST["to_more"]) ? $_POST["to_more"] : array();
$ar = array_filter($ar, function($el){ return !empty($el);});
echo count($ar);
?>
Should be quicker than foreach, btw.
UPD: Oh, seems, NLSaini posted the precise solution, check it.

PHP Multiple form in same page

I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>

Dynamic Error Display

Please is there a way i can make my error display dynamic for only the fields that have errors display under each textbox.
The I normally use displays only one error for all of the fields when one field is empty...
Thanks
if (isset($_POST['submit'])) {
$a = mysql_real_escape_string($_POST ['a']);
$b = mysql_real_escape_string($_POST ['b']);
$c = mysql_real_escape_string($_POST ['c']);
$d = mysql_real_escape_string($_POST ['d']);
$e = mysql_real_escape_string($_POST ['e']);
if (($a == "") || ($b == "") || ($c == "") || ($d == "") || ($e == "")) {
echo "<div id=\"content\" >" ;
echo "<div class=\"error\" >" ;
echo "empty";
echo "</div>";
echo "</div>";
} else {
$query = "INSERT INTO user (a, b, c, d, e)
VALUES ($a, $b, $c, $d, $e)";
mysql_query($query);
}
}
?>
Enter Texts <br/>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="post">
A:<input type="text" name="a" ><br/>
B:<input type="text" name="b" ><br/>
C:<input type="text" name="c" ><br/>
D:<input type="text" name="d" ><br/>
E:<input type="text" name="e" ><br/>
<input type="submit" name ="submit" value="Go"/>
</form>
thank you.
Here is an alternative way todo it, checking and building upon an error array as you go, then if the error array is empty do query.
<?php
//Check form was posted
if($_SERVER['REQUEST_METHOD']=='POST'){
//Pre build allowed array
$allowed=array('a','b','c','d','e','submit');
//Pre build errors array
$errors=array('A was not set',
'B was not set',
'C was not set',
'D was not set',
'E was not set');
//Create Blank error array
$error=array();
//Loop through the POST
foreach($_POST as $key=>$value){
//If key is in allowed array
if(in_array($key,$allowed)){
//Check its at good length
if(strlen(trim($value)) >= 1){
//Assign variable variable the key and value + escape
$$key = mysql_real_escape_string(trim($value));
}else{
//Assign key/value null
$$key = null;
//Assign the error from the errors array to the output error array
$error[$key] = $errors[array_search($key,$allowed)];
}
}else{
$error=array('Rouge POST key');
}
}
//If all is good do query
if(empty($error)){
$query = "INSERT INTO user (a, b, c, d, e)
VALUES ($a, $b, $c, $d, $e)";
mysql_query($query);
}
}?>
Enter Texts <br/>
<form action="" method="post">
A:<input type="text" name="a" ><?php echo (isset($error['a'])?$error['a']:null)?><br/>
B:<input type="text" name="b" ><?php echo (isset($error['b'])?$error['b']:null)?><br/>
C:<input type="text" name="c" ><?php echo (isset($error['c'])?$error['c']:null)?><br/>
D:<input type="text" name="d" ><?php echo (isset($error['d'])?$error['d']:null)?><br/>
E:<input type="text" name="e" ><?php echo (isset($error['e'])?$error['e']:null)?><br/>
<input type="submit" name="submit" value="Go"/>
</form>
Instead of showing error at top, attach following piece of code with each field. It will not show error on form load if your form and action code is on same page.
Try something like this:
A:<input type="text" name="a" ><br />
<?php if( isset($_POST['a']) && trim($_POST['a']) == '' ) { echo 'This field is required'; } ?>
B:<input type="text" name="b" ><br/>
<?php if( isset($_POST['b']) && trim($_POST['b']) == '' ) { echo 'This field is required'; } ?>
C:<input type="text" name="c" ><br/>
<?php if( isset($_POST['c']) && trim($_POST['c']) == '' ) { echo 'This field is required'; } ?>
D:<input type="text" name="d" ><br/>
<?php if( isset($_POST['d']) && trim($_POST['d']) == '' ) { echo 'This field is required'; } ?>
E:<input type="text" name="e" ><br/>
<?php if( isset($_POST['a']) && trim($_POST['a']) == '' ) { echo 'This field is required'; } ?>
Instead of checking all variables at once in ($a == "") || ($b == "") || ($c == "") || ($d == "") || ($e == "") check them one at a time and set individual error variables. Use these to display error messages close to your input field.
For example:
if ( $a == "" ) { $errorA = true; }
A:<input type="text" name="a" ><br/>
<?php print ($errorA ? '<span class="error">A is empty.</span><br/>' : ''); ?>
To prevent the form from being submitted, you could rather use following lines:
$error['A'] = $error['B'] = $error['C'] = .... = $error['Z'] = 0;
if ( $a == "" ) { $error['A'] = 1; }
if ( array_sum($error) > 0 ) {
// do not submit!
}
A:<input type="text" name="a" ><br/>
<?php print ($error['A'] ? '<span class="error">A is empty.</span><br/>' : ''); ?>
Or you simply set a broader error variable like this:
$error = false;
if ( $a == "" ) { $errorA = true; $error = true; }
if ( $b == "" ) { $errorB = true; $error = true; }
if ( !$error ) { //submit form
}
A:<input type="text" name="a" ><br/>
<?php print ($errorA ? '<span class="error">A is empty.</span><br/>' : ''); ?>

Categories