I want to check user input in the textbox. If the first character is a zero, it will be replaced with +63
. But it should not replace all the zeroes in the string. I had search through sites but most are about replacing all of the occurrences. Thanks a lot!
JavaScript solution
var str = "000123";
var foo = str.replace(/^0/,"+63");
alert(foo);
Basic regular expression
PHP Solution
$string = '000123';
$pattern = '/^0/';
$replacement = '+63';
echo preg_replace($pattern, $replacement, $string);
In PHP:
<?php
$ptn = "/^0/"; // Regex
$str = "01234"; //Your input, perhaps $_POST['textbox'] or whatever
$rpltxt = "+63"; // Replacement string
echo preg_replace($ptn, $rpltxt, $str);
?>
Would echo out:
+631234
Of course, you'll want to validate the input and everything, but that's how you'd replace it after it's been submitted.
Something like this:
if(oldStr.charAt(0) == "0") {
newStr= oldStr.replace(oldStr.charAt(0), "+63");
}
Btw its JS solution
I recommend avoid Regex in your code if you can due to performance overhead. It's easy to make it in PHP without Regex:
if($str[0] == "0"){
$str = substr_replace($str,'+63',0,1);
}
$numbers='012345';
1.first check the first digit is zero or not,
if (preg_match('/^0/', $numbers))
2.if zero,then remove zero and add the required data with the variable
$str=ltrim ($numbers, '0');
$mobile ='+63'.$str;
so the output will be,
+6312345
If I understand everything correctly this should work for you:
<input type="text" id="txt" value="0 is the score" />
Javascript:
var str = document.getElementById("txt").value;
if(str[0] === '0') {
document.getElementById("txt").value = "63" + str.substring(1);
}
See demo : http://jsfiddle.net/rZ3vm/
Also see string functions in javascript and the substring function.
var str = "000123";
var foo = str.charAt(0).replace("0","+63") + str.substr(1);
alert(foo);
Some thing like this ....
var string = "0230234";
var newString = string.indexOf('0') == 0 ? string.substring(1) : string;
newString = "+63"+newString
alert(newString); // +63230234
str=(str.charAt(0)=='0')?(str.replace(str.charAt(0),"+63")):str;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.