Translate javascript string replace function to php - javascript

I found in this site a very basic javascript function to encode text. Looking at the source code this is the string replacement code:
txtEscape = txtEscape.replace(/%/g,'#');
So the string stackoverflow becomes #73#74#61#63#6B#6F#76#65#72#66#6C#6F#77
I need a function that does the same elementary encryption in php, but I really don't understand what the /%/g does. I think in php the same function would be something like:
str_replace(/%/g,"#","stackoverflow");
But of course the /%/g doesn't work

Replace a character
Indeed, the PHP function is str_replace (there are many functions for replacements). But, the regex expression is not the same :)
See official documentation: http://php.net/manual/en/function.str-replace.php
In your case, you want to replace a letter % by #.
g is a regex flag. And // are delimiter to activate the regex mode :)
The "g" flag indicates that the regular expression should be tested against all possible matches in a string. Without the g flag, it'll only test for the first.
<?php
echo str_replace('%', '#', '%73%74%61%63%6B%6F%76%65%72%66%6C%6F%77');
?>
In PHP, you can use flags with regex: preg_replace & cie.
Escape
See this post: PHP equivalent for javascript escape/unescape
There are two functions stringToHex and hexToString to do what you want :)
Indeed, the site you provided use espace function to code the message:
document.write(unescape(str.replace(/#/g,'%')));

Related

Javascript Regex vs Java Regex

I have a a regex in Javascript that works great: /:([\w]+):/g
I am working on converting my javascript app to java, and I know to escape the \ using \ i.e. /:([\\w]+):/g, yet my tests are still returning no match for the string "hello :testsmilie: how are you?"
Pattern smiliePattern = Pattern.compile("/:([\\w]+):/g");
Matcher m = smiliePattern.matcher(message);
if(m.find()) {
System.println(m.group(0));
}
In javascript it returns ":testsmilie:" just fine, so i'm not sure what the difference is. Any help would be much appreciated!
Your regex in java can just be :
Pattern.compile(":[^:]+:")
Which match : followed by one or more no two dots : followed by :
Or if you want to use \w you can use :
Pattern.compile(":\\w+:")
If you note you don't need parenthesis of group (), so to get the result you can just use :
System.out.println(m.group());
You should learn how is made a Javascript regex, because the / are the delimiters of the real regex, and g is a modifier for global
In Java the equivalent is: :([\\w]+):, and no need of global flag as you just need to call multiple times .find() to get all the matches
You should take a look at regex101 which is a good website to test regex

RegEx that works in Javascript won't do so in PHP

I will try to make my question short yet understandable, I have a simple RegEx I use in javascript to check for characters that aren't alphanumeric (AKA Symbols). It would be "/[$-/:-?{-~!"^_`[]]/"
In javascript, doing
if(/[$-/:-?{-~!"^_`\[\]]/.test( string ))
just works, if any of those characters are in the string, it will give true, else, it will give false. I tried to do the same in PHP, the following way
if(preg_match('/[$-/:-?{-~!"^_`\[\]]/', $string ))
other regexes work when done this way, but this particular one simply will give false no matter what when ran in PHP.
Is there any reason to this? Am I doing something wrong? Does PHP comprehend regexes in a different way? What should I change to make it work?
Thanks for your time.
Since php uses PCRE, you will get a pattern error using delimiter / as seen here http://regex101.com/r/3ILGgE/1
So, it should be escaped correctly.
Using / as the delimiter, the string is
'/[$-\/:-?{-~!"^_`\[\]]/'
Using ~ as the delimiter, the string is
'~[$-/:-?{-\~!"^_`\[\]]~'
Also, be aware you have a couple of range's in the class $-/ and :-? and {-~
that will include the characters between the from/to range characters as well
and does not include the range character - itself as it is an operator.

Converting Ruby regex to JavaScript one

I would like to convert this Ruby regex to JavaScript one:
/\<br \/\>\<a href\=(.*?)\>([0-9]+\:[0-9]+)\<\/a\> \<a href\=\'.*?\' target\=\_blank\>(.*?)(?=\<\/a\>\<br\>\<p.*?\<\/p\>\<br \/\>\<a href\=.*?\>([0-9]+\:[0-9]+)\<\/a\> \<a href\=\'.*?\' target\=\_blank\>.*?\<\/a\>.*?\<br \/\>)/m
It works perfectly in Ruby, but not in the Chrome JavaScript console. Then I will use it to extract some information from a webpage source HTML code (document.body.innerHTML) with a JavaScript function using this scan method described here: JavaScript equivalent of Ruby's String#scan
I think the lookahead (?= ) may be problematic in JavaScript, on the top of that it contains a capture group. Can it be converted at all?
In JavaScript you could do the following:
var re = new RegExp("<br /><a href=(.*?)>([0-9]+:[0-9]+)</a> <a href='.*?' target=_blank>(.*?)(?=</a><br><p.*?</p><br /><a href=.*?>([0-9]+:[0-9]+)</a> <a href='.*?' target=_blank>.*?</a>.*?<br />)", "m");
But this likely will not work the same because the m modifier in Ruby makes the . match all characters while in JavaScript this means multi-line mode where ^ and $ match at the start and end of each line.
So if you really think you need regex to do this and the HTML data you are matching has or could have line breaks, you will need to remove the m flag and replace .*? with a workaround such as [\S\s]*? to match those characters as well since JavaScript does not have a dotall mode modifier that works like the Ruby m modifier.

JavaScript Regular Expression to find PHP tags

I have googled for a regex to grab and also read a few tutorials and I can't seem to get a solid regular expression to do this.
What I need to do is write a JavaScript regular expression that will match PHP tags within a string.
I have inherited a large php project where the views that have mixed html and php are not very readable. So what I'm doing is writing an IDE extension for my own personal use to strip out php that is mixed in a php view in order to run an HTML indentation script on it without confusing the HTML indentation script. Then after the indentation script has finished I go back and re-insert the php again.
What I have so far is this (I converted this from a regex that looks for brackets [], I knew it wouldn't match everything but it got me far enough to flesh out my IDE extension):
var php_tag_pattern = /<\?[^<>]*\?>/;
Now for obvious reasons it is not matching on code like this:
<?=$common->format_number($acct_info['number'])?>
or this:
<?
$wifi = $wifi_lib->wifi_radius($v['radiusgroupname']);
if (!empty($wifi)) :?>
I have been messing around with this for the last several hours so I thought I would finally ask for help to see what I'm missing.
Thanks!
To match multi-line php text you will need an implementation of DOTALL in Javascript. Unfortunately Javascript doesn't have s flag but there is a workaround. Try this code:
var php_tag_pattern = /<\?[=|php]?[\s\S]*?\?>/;
[\s\S] will make sure to match php text in multi line including new lines as well.
var php_tag_pattern = /<\?=?.+?\?>/;
var regex = /<\?[=|php]?[^<>]*\?>/;
You will also need to use the multiline modifier new RegExp(regex, "gim"). The 'g' is global, 'i' is case insensitive and 'm' multiline.

Regular expression for browser Url

I am new to JavaScript
i need a regular expression which
allows both of this forms
for example :
http://www.google.com
www.google.com
var url_pattern = new RegExp("((ftp|http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?", "i");
return url_pattern.test(url);
(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?
This works quite well.
I've just written up a blog post on recognising URLs in most used formats such as:
www.google.com
http://www.google.com
mailto:somebody#google.com
somebody#google.com
www.url-with-querystring.com/?url=has-querystring
The regular expression used is /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/ however I would recommend you got to http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the to see a complete working example along with an explanation of the regular expression in case you need to extend or tweak it.
^((?:(?:https?|ftp):)?\/\/?)?(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$
Test it! https://regex101.com/r/qQ8uV6/1
Extracted from In search of the perfect URL validation regex https://mathiasbynens.be/demo/url-regex (modified it a bit).
credits to #diegoperini.
If you test it in JavaScript, you'll get a nice
ParseError: Error parsing regular expression: Invalid regular expression
....
Range out of order in character class
You need to replace \x{xxxx} for \uxxxx. So in JavaScript it'll be:
^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\ufff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$
Just like stated in JavaScript Unicode Regex - Range out of order in character class

Categories

Resources