Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript Doubt 1

Status
Not open for further replies.

subin83

Programmer
Aug 7, 2010
5
DE
Hello Javascript Guru's,

I have a query with the following javascript snippet. I would be very helpful if someone can give me some pointers.
Can you please let me know what the function(matchstr,parens) means? Which function would it call? There is no code above or below thats relevant to this excpet the function dec2char.

str = str.replace(/&#([0-9]{1,7});/g,
function(matchstr, parens) {
return dec2char(parens);
}
);
I dono if this is the correct forum to ask, but I need to convert this logic to php. If someone has any pointers as how the function(matchstr,parens) can be converted please let me know that also.

Thanks a lot :)

Regards,
Subin
 
[0]
>str = str.replace(/&#([0-9]{1,7});/g,
Maybe you've to take a magnifying glass in some situation.
It should mean this instead.
[tt]str = str.replace(/&#([0-9]{1,[red]2[/red]});/g, [/tt]
[1]
>Can you please let me know what the function(matchstr,parens) means?
It means this: when a match occurs, the (anonymous) function will be called with the passing of arguments operates like this:
[ul][li]arguments[0]: the whole match (matchstr)[/li]
[li]arguments[1]: the first submatch (match the parenthesized pattern)[/li]
[li]arguments[2]: etc... can be more if appropriate[/li][/ul]
[2] The function dec2char() is an external function (trying to hide?) It can mean very simply String.fromCharCode()! Hence, it can simply be written like this in the js version.
[tt]
str = str.replace(/&#([0-9]{1,7});/g,function(v0,v1) {return String.fromCharCode(v1);});
[/tt]
[3] In php, you've the same construction using mpreg_replace_callback. It is like this.
[tt]
$str=preg_replace_callback('/&#([0-9]{1,2});/', create_function('$argv','return dec2char($argv[1]);'),$str);
[/tt]
[3.1] Note: g flag taken out.

[4] In the deflated version, in analogy with [2] that I think what it means dec2char(), it would look like this.
[tt]
$str=preg_replace_callback('/&#([0-9]{1,2});/', create_function('$argv','return chr($argv[1]);'),$str);
[/tt]
 
Thanks a lot tsuji for the detailed explanation.

Regards,
Subin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top