Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace First Character PHP

Tags:

php

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!

like image 387
Brandon Young Avatar asked Mar 05 '12 04:03

Brandon Young


2 Answers

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.

like image 101
opes Avatar answered Sep 18 '22 20:09

opes


JavaScript solution

var str = "000123";
var foo = str.replace(/^0/,"+63");
alert(foo);

Basic regular expression

  • ^ - match beginning of a string
  • 0 - match the number zero

PHP Solution

$string = '000123';
$pattern = '/^0/';
$replacement = '+63';
echo preg_replace($pattern, $replacement, $string);
like image 42
epascarello Avatar answered Sep 20 '22 20:09

epascarello