April 21, 2015

Extract Top Level Domain from Domain name

Joao Alves’s Question:

I have an array of top level domains like:

['ag', 'asia', 'asia_sunrise', 'com', 'com.ag', 'org.hn']

Given a domain name, how can i extract the top level domain of the domain name based on the array above? Basically i dont care of how many levels the domain has, i only need to extract the top level domain.

For example:

test1.ag -> should return ag

test2.com.ag -> should return com.ag

test.test2.com.ag -> should return com.ag

test3.org -> should return false

Thanks

Updated to incorporate Traxo’s point about the . wildcard; I think my answer is a little fuller so I’ll leave it up but we’ve both essentially come to the same solution.

//set up test variables
$aTLDList = ['ag', 'asia', 'asia_sunrise', 'com', 'com.ag', 'org.hn'];
$sDomain = "badgers.co.uk"; // for example

//build the match
$reMatch = '/^.*?.(' . str_replace('.', '.', implode('|', $aTLDList)) . ')$/';
$sMatchedTLD = preg_match($reMatch, $sDomain) ? 
        preg_replace($reMatch, "$1", $sDomain) : 
        "";

Resorting to Regular Expressions may be overkill but it makes for a concise example. This will give you either the TLD matched or an empty string in the $sMatchedTLD variable.

The trick is to make the first .* match ungreedy (.*?) otherwise badgers.com.ag will match ag rather than com.ag.

parseurl() function gives you access to the host name of the url. You can use that to process the host name and find out the tld.

$url = 'http://your.url.com.np';
var_dump(parse_url($url, PHP_URL_HOST));

Next steps could be using explode() to split the host name and checking the last item in the exploded list. But I am going to leave that to you.

March 18, 2013

jQuery remove email in textarea

Question by JR Galia

I have HTML textarea.

<textarea> ... </textarea>

I don’t want users to enter any email address in the textarea. What is the best approach on this using jQuery? How to remove email entered before submitting the form?

I only need hint and references. Thanks.

Answer by nbrooks

jsFiddle Demo

Use a regular expression to match the email addresses, and then replace them with blank strings.

$(function() {
    $("textarea").change(function() {
        $(this).val( function(idx, val) {
            return val.replace(/b(w)+@(w)+.(w)+b/g, "");
        });
    });
});

Answer by Starx

Although a genuine concern, the use of JavaScript here will not give you the result you are expecting. The problem is that you want to remove the email addresses automatically before you are submitting the form. This is not a user friendly approach.

You have to alert the user that he cannot enter a email address in the box and ask him to correct the mistake.

Removing the email address part is MUCH SAFER DONE IN SERVER Level. Like from PHP, ASP, JSP etc.

Alert the user of email address like this.

$("textarea").change(function() {
    if(/^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/.test($(this).val()) {
         alert('you have entered email address, which is not allowed');
    }
});

Then remove the email for your Server Application.

November 1, 2012

Extacting words between $ symbol

Question by rajesh

I want to extract the words between the symbol $.

String = " this is first attribute $color$. this is the second attribute $size$"

I want to get a string list as List =[color , size]

I have used

Pattern pattern = Pattern.compile("(\$) .* (\$)");
Matcher matcher = pattern.matcher(sentence);

but I get the out put as

"$color$.this is the second attribute $size$"

please help me to solve this problem

Answer by halex

The problem is that the regex you are using is greedy and consumes everything beginning at the first $ until the last $ in your string. You have to add a ? after the * to make the regex nongreedy:

Pattern pattern = Pattern.compile("\$(.*?)\$");
Matcher matcher = pattern.matcher(sentence);
List<String> result = new ArrayList<String>();
for(int i=1; i <= matcher.groupCount(); i++)
    result.add(matcher.group(i);

Answer by Starx

Try this regex. It should give what is expected.

Pattern pattern = Pattern.compile("$(.*?)$");
August 12, 2012

Regular Expression, match ${ANY_TEXT}

Question by CappY

Can you please help me with reg ex. I cant make it 🙁 I hate regex.
I need to match this string ${ANY_TEXT} .Exactly one “${” and exactly one closing tag “}”.

Thanks a lot. 🙂

Answer by Shi

${[^}]+} will match it. It will match ${ABC} from ${ABC}}} as well. If you want to match complete lines, simply anchor the regular expression using ^${[^}]+}$.

A good site to learn regular expressions is http://www.regular-expressions.info/.

Answer by Starx

I suppose this covers all the texts.

/^${[a-zA-Z]}$/
May 28, 2012

PHP Currency Regular Expression

Question by Lee

I am trying to find a piece of regex to match a currency value.

I would like to match only numbers and 1 decimal point ie

Allowed

  • 10
  • 100
  • 100.00

Not Allowed

  • Alpha Characters
  • 100,00
  • +/- 100

I have search and tried quite a few without any luck.

Hope you can advise

Answer by The Pixel Developer

if (preg_match('/^[0-9]+(?:.[0-9]+)?$/im', $subject))
{
    # Successful match
}
else
{
    # Match attempt failed
}

Side note : If you want to restrict how many decimal places you want, you can do something like this :

/^[0-9]+(?:.[0-9]{1,3})?$/im

So

100.000

will match, whereas

100.0001

wont.

If you need any further help, post a comment.

PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.

Answer by Starx

How about this

if (preg_match('/^d+(.d{2})?$/', $subject))
{
   // correct currency format
} else {
  //invalid currency format
}
May 6, 2012

RegEx for <title> with leading, trailing, linebreak

Question by user1377738

Most website I can parse its title easily with RegEx “(.)” or “s(.+?)s*”. However some sites have a bit different formatting, like http://www.youtube.com (see below). The expression above does not work. Any help catching this kind of format and any other HTML formats?

Thanks
-Tim.

<title>
  YouTube - Broadcast Yourself.

Answer by Fèlix Galindo Allué

If you want to include the line break to the regular expression, in most cases you would only need to use the n inside the expression. That said, which language/interpreter are you using? Some of them doesn’t allow multiline expressions.

If they are permitted, something like (.|n|r)* would suffice.

In case your language or interpreter is not compatible to multiline regular expressions, you could always replace the newlines characters with spaces, and then pass the resulting string to the regular expression parser. That again also depends on your programming environment.

Hope helped!

Answer by Starx

There are various ways to get this done. For only title, SIMPLEHTMLDOM is more than enough.

$html = file_get_html('http://www.youtube.com/');
$title = $html -> find("title") -> innerHTML;
echo $title;
May 5, 2012

Jquery contains selector, regex

Question by Jernej Pangeršič

This is my code:
Let’s say that name is set to john

$("#first_table").append($('#second_table').find("tr:contains(" + name + ")"));

Basically I have 2 tables on my website. I would like to move elements from first to second, but only if they match completely. How can i do that?

Now if I have (for example) john john #1, john #2 in my table, they would all be moved. I would only like to move john and leave john #1 and john #2
Thanks!
EDIT:
I would like the code to work to match the variable name EXACTLY.
So if name is JOHN it must only get JOHN. If it’s JOHN #1, it must only get JOHN #1 and so on. Is this possible?

Answer by Starx

Since every name case is valid to :contains(" + name +") statement, it matches all of them.

Try this, with a :not to omit the one with “#”

$("#first_table").append($('#second_table').find("tr:contains(" + name + "):not(:contains('#'))"));

Update:

If you want to be precise about the values inside. Then use something like this

$("#second_table tr td").each(function() {
   if($(this).text() == 'John') { 
     $(this).closest("tr").appendto($("#first_table")); //find the cotaining tr and append to another table
   }
});
April 20, 2012

Prevent links from auto hyperlinking in Outlook etc using PHP

Question by Ben Carey

I know that this can be done using settings in Outlook, but that only sorts the issue for myself.

What I would like to do is use PHP to prevent text from being hyperlinked just because there is an @ sign etc…

As far as I can see, the only option for me is to encode all @ signs to their HTML numeric entity like so:

Something like this:

$message = str_replace('@','&#64;',$message);

However, if possible, I do not want this to happen if the @ sign is part of an email address.

Therefore I need something like this:

// SOME_REGEX will match any @ sign that is NOT part of an email address
$message = preg_replace('SOME_REGEX','&#64;',$message);

Can anybody think of any other better methods? Are there any flaws in this plan? Can anyone suggest a good regular expression for this? I am struggling to write a regex that matches an @ sign if it is not part of an email address

Thanks in advance

Answer by Anthony

This will not work if the email address is wrapped in anything not defined in the trim list.

$chunked_message = explode(" ", $message);

foreach($chunked_message as $chunk) {
    $clean_chunked_message[] = 
               (!filter_var(trim($chunk, " -().?!trn", FILTER_VALIDATE_EMAIL)) 
               ? str_replace('@', '&#64;' $chunk) : $chunk;
}

$clean_message = implode(" ", $clean_chunked_message);

Good luck.

Answer by Starx

This is a feature of mail application to detect link when it is found and make it click able.

A dirty trick to escape this situation is to use space in between the links.

Example:

http://ww w.you tube.com/v=.......
April 16, 2012

regex to allow decimals, but no commas

Question by Rookieatthis

I need a regex expression that allows decimals but no commas. Such as:
1200.00
or
50.00
or
40
or
1
The expression is used in a validation to make sure people put in a price as a number, but no commas. I currently have a regex that allows for commas, numbers, and decimals, but I cannot seem to get the commas out.

This is the current regex that I have which doesnt allow commas or decimals, but I want decimals in there

/^[0-9 ]+$/,

Thanks for your help.

Answer by npinti

Something like this should work: ^d+(.d{2})?$

This basically states the following:

  • ^d+: Start from the beginning of the string (^) and match one or more digits (d+).
  • (.d{2})?: Match a period character (.) followed by exactly 2 digits (d{2}). The question mark denotes that the value within the brackets can either exist or not, meaning that it will match either 1 or 0 instances of the pattern.
  • $: The string must end here.

Answer by Starx

To match the currency you can use this regex

^(?:[1-9]d+|d)(?:.dd)?$
April 12, 2012

Jquery custom validation non numeric

Question by Brian Perin

I’m trying to write a custom validation function for jquery. The rule should be that the field cannot ONLY be numeric. I know how to write only numeric or only alpha but I want the rule to say that a value of “12345” would fail, but “12345A” would be validated

This is what I have for non numeric

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !value.match(/[0-9]+/);
},"Only alphabatic characters allowed.");

but I can’t figure out how to do not ONLY numeric.


Working script

Here are three rules that might be helpful, the last one is the one that answers this question.

 jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
}, "No spaces please");

jQuery.validator.addMethod("alpha", function(value, element) {

    return this.optional(element) || /^[a-z]+$/i.test(value);
},"Letters only please.");

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || isNaN(Number(value));
},"String cannot be numeric");

Answer by Elliot Bonneville

Use parseInt (which returns NaN if the operand isn’t strictly a number) like this:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(parseInt(value));
},"Only alphabatic characters allowed.");

Don’t use != in this case or you could wind up with this unpleasant situation.


According to Ken Browning‘s comment, parseInt might not be appropriate here. Try this instead:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(Number(value));
},"Only alphabatic characters allowed.");

Answer by Starx

I think this regex should be enough

/[a-z]/i.test(value);

Usage

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !(/[a-zA-Z]/i.test(value));
},"Only alphabatic characters allowed.");
...

Please fill the form - I will response as fast as I can!