Replace every instance of a substring in PHP
<?php
if(isset($_GET['submit']))
{
if(strlen($_GET['text']) && strlen($_GET['search_for']) && strlen($_GET['replace_with']))
{
$text = $_GET['text'];
$search_for = $_GET['search_for'];
$replace_with = $_GET['replace_with'];
$offset = 0;
$search_for_length = strlen($search_for);
$replace_with_length = strlen($replace_with);
$text = ' '.$text; // that's how search position will never be 0
while($search_for_position = strpos($text, $search_for, $offset))
{
$text = substr_replace($text, $replace_with, $search_for_position, $search_for_length);
$offset = $search_for_position + $replace_with_length; // that's how $search_for will not be found in $replace_with when $search_for actualy exists in $replace_with
}
echo $text.'<hr/>';
}
else
{
echo 'Please fill up all the form input.<hr/>';
}
}
?>
<form action="index.php" method="get">
<textarea name="text" id="" cols="30" rows="5">Write something here.....</textarea><br/><br/>
Search for:<br/>
<input type="text" name="search_for" /><br/><br/>
Replace with:<br/>
<input type="text" name="replace_with" /><br/><br/>
<input type="submit" name="submit" value="Search and Replace" />
</form>
<!-- Note: We can also create this program using str_replace function -->
if(isset($_GET['submit']))
{
if(strlen($_GET['text']) && strlen($_GET['search_for']) && strlen($_GET['replace_with']))
{
$text = $_GET['text'];
$search_for = $_GET['search_for'];
$replace_with = $_GET['replace_with'];
$offset = 0;
$search_for_length = strlen($search_for);
$replace_with_length = strlen($replace_with);
$text = ' '.$text; // that's how search position will never be 0
while($search_for_position = strpos($text, $search_for, $offset))
{
$text = substr_replace($text, $replace_with, $search_for_position, $search_for_length);
$offset = $search_for_position + $replace_with_length; // that's how $search_for will not be found in $replace_with when $search_for actualy exists in $replace_with
}
echo $text.'<hr/>';
}
else
{
echo 'Please fill up all the form input.<hr/>';
}
}
?>
<form action="index.php" method="get">
<textarea name="text" id="" cols="30" rows="5">Write something here.....</textarea><br/><br/>
Search for:<br/>
<input type="text" name="search_for" /><br/><br/>
Replace with:<br/>
<input type="text" name="replace_with" /><br/><br/>
<input type="submit" name="submit" value="Search and Replace" />
</form>
<!-- Note: We can also create this program using str_replace function -->
Comments
Post a Comment