Interviewer And Interviewee Guide

PHP Interview Question:

How To Replace a Substring in a Given String in PHP?

Submitted by: Administrator
If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():

<?php
$string = "Warning: System will shutdown in NN minutes!";
$pos = strpos($string, "NN");
print(substr_replace($string, "15", $pos, 2)." ");
sleep(10*60);
print(substr_replace($string, "5", $pos, 2)." ");
?>

This script will print:

Warning: System will shutdown in 15 minutes!
(10 minutes later)
Warning: System will shutdown in 5 minutes!

Like substr(), substr_replace() can take negative starting position counted from the end of the string.
Submitted by: Administrator

Read Online PHP Job Interview Questions And Answers
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.