Friday, January 13, 2012

replace function js to php


I am trying to change a js program to php. there is a replace function like $t = t.replace(/B/g, "b");



if i change this to php as $t = str_ireplace(/B/g, "b",$t);



it shows error about "unexpecting '/' ". how to solve this.

2 comments:

  1. First, JavaScript's replace function is closest to preg_replace.

    Second, if you read the docs for str_ireplace, it's case-insensitive replace, which given that you're trying to turn B into b is precisely the wrong function to use.

    You can do $t = str_replace('B', 'b', $t); (simpler) or $t = preg_replace('/B/', 'b', $t); (can handle more complex situations than what you're doing).

    ReplyDelete
  2. That call to Javascript replace uses a regular expression as the search criterion.

    The PHP Equivalent is preg_replace

    ReplyDelete