PHP preg_replace with any variation of upper/lowercase? - preg-replace

I needed to write a custom module in drupal to help out with my location search. Initially I simply needed to remove a comma from queries, and then I realized that I would need to replace all instances of states with their abbreviation (California -> CA) because of how information is stored in my database. However, upon doing this I found out that my method of using preg_replace seems to be dependent on upper/lowercase. So in this line:
$form_state['values'] = preg_replace("/alabama/", 'al', $form_state['values']);
"alabama" will be replaced with "al", but "Alabama" or "ALABAMA" will not. Is there a way to replace any instance of Alabama with its abbreviation without accounting for every possible variation in casings?

you can try also str_ireplace() it's Case-insensitive
<?php
$str = 'alabama ,Alabama,ALABAMA';
$replace = str_ireplace('alabama','al',$str);
echo $str;
echo "<br/>";
echo $test;
?>

$form_state['values'] = preg_replace("/alabama/i", 'al', $form_state['values']);
The 'i' modifier will make the pattern case-insensitive.

Related

Why preg_replace() function isn't working properly?

My PHP Script is:
<?php
$string = '{controller}/{action}';
$pattern = '/\{([a-z]+)\}/i';
$replacement = '(?P<$1>[a-z-]+)';
echo preg_replace($pattern, $replacement, $string);
?>
it is showing this result:
(?P[a-z-]+)\/(?P[a-z-]+)
I am expecting this:
(?P<controller>[a-z-]+)\/(?P<action>[a-z-]+)
How I can able to do this??
Your code produces the correct result, that is,
(?P<controller>[a-z-]+)\/(?P<action>[a-z-]+)
The problem is: when you echo that out and display it in a browser, the browser interprets <controller> and <action> as HTML tags, like <p> or <strong>. So, it doesn't display them; it only displays what is left:
(?P[a-z-]+)\/(?P[a-z-]+)
You would see the correct result if you ran this script from the command line. To make it work in the browser, you need to replace the last line with
echo htmlentities(preg_replace($pattern, $replacement, $string));

Why Laravel Request object is replacing spaces with underscores on my form names?

I have a Form posting variables containing spaces in their names
e.g.
I perform my ajax request and i can see in chrome inspector that name is correctly passed "with blank space)
In my api.php:
Route::post('/user', 'UserController#get');
UserController
function get(Request $request)
{
dd($request->input('Name Surname')); //display null
dd($request->all()); //I notice the key's changed to Name_Surname
}
Taken that I can't change the names because they have to contain spaces (bad practice? ok but it has to be like that):
how can I avoid spaces to be replaced?
(maybe without to have to manipulate the request->all() returned array keys by hand....)
Short answer I don't believe there to be such a way.
You can map the response with a bit of string replace though:
$data = $request->all()->mapWithKeys(function($item, $key) {
return [str_replace("_", " ", $key) => $item];
});
If it's something you want to apply across the board, you could possible rig up some middleware to apply it to all requests.
If previous answer not work for you, try this:
$data = collect($request->all())->mapWithKeys(function($item, $key) {
return [str_replace("_", " ", $key) => $item];
})->toArray();
You may also normalize the Input Name if it is known...
$field_name = 'FIELD NAME WITH SPACES';
$value = request( str_replace( ' ', '_', $field_name ) );

XML::Twig : how to specify a twig_handler for a <_tag> which starts with an underscore?

I have an XML file whose root element tag is <__> (two underscores). When, however, that tag name is used in the twig_handlers list XML::Twig->new dies with the error message:
unrecognized expression in handler: '__'
Actually, ANY tag starting with an underscore produces this error except for Twig's special tags _all_ and _default_, either of which I can use to process the file at the expense of throwing away all the handler callbacks except the last.
The invocation which fails is:
XML::Twig->new (twig_handlers => { '__' => \&show })
I imagine there's an XML::Twig Xpath expression which can be used here but the CPAN documentaton is pretty vague about their syntax. I also now wonder what I'd have to do to get at an element <_all_> :)
If anyone has a suggestion it would be much appreciated.
The problem only occurs when the twig is created since once processing has started (using the callback expression _all_), <__> elements at any level in the input are processed normally.
If anyone wants to play with the problem, here's the program I was using to try finding a solution. Set $xpath to the expression you want to test.
use strict;
use XML::Twig;
my $xpath = '_all_'; # <---- fails if one puts '__' here
my $xml = <<EOS; # <---- here's the XML data to process
<__>
<AA>first</AA>
<__>second</__>
</__>
EOS
sub show {
print "handler called for element ", $_->gi, ", whose children are\n";
my #children = $_->children;
for my $elt (#children) {
print "\t", $elt->gi, " holds \"", $elt->text, "\"\n";
}
1;
}
my $twig = XML::Twig->new (twig_handlers => { $xpath => \&show });
$twig->parse ($xml);
Which version of XML::Twig are you using? This is a bug that was fixed in version 3.38.
From the Changes file:
version 3.38
date: 2011-02-27
# minor maintenance release
fixed: RT 65865: _ should be allowed at the start on an XML name
https://rt.cpan.org/Ticket/Display.html?id=65865
reported by Steve Prokopowich
And indeed when I use '__' as the value for $xpath the code runs without errors, and gives the correct output.

ReCaptcha Implementation in Perl

To implement recaptcha in my website.
One option is google API . But for that i need to signup with domain name to get API key.
Is there any other way we can do it ?
You don't necessarily need a domain name to sign up, per se.
They have a concept of a "global key" where one single domain key would be used on several domains. When signing up, select the "Enable this key on all domains (global key)" option, and use a unique identifier (domainkey.abhilasha.com) and this will be fine, you can use the key from any domain in the end.
One way: add this code to your perl file that is called by an html form:
Simplified of course
my #field_names=qw(name branch email g-recaptcha-response);
foreach $field_name (#field_names)
{
if (defined param("$field_name"))
{
$FIELD{$field_name} = param("$field_name");
}
}
$captcha=$FIELD{'g-recaptcha-response'};
use LWP::Simple;
$secretKey = "put your key here";
$ip = remote_host;
#Remove # rem to test submitted variables are present
#print "secret= $secretKey";
#print " and response= $captcha";
#print " and remoteip= $ip";
$URL = "https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip;
$contents = get $URL or die;
# contents variable takes the form of: "success": true, "challenge_ts": "2016-11-21T16:02:41Z", "hostname": "www.mydomain.org.uk"
use Data::Dumper qw(Dumper);
# Split contents variable by comma:
my ($success, $challenge_time, $hostname) = split /,/, $contents;
# Split success variable by colon:
my ($success_title, $success_value) = split /:/, $success;
#strip whitespace:
$success_value =~ s/^\s+//;
if ($success_value eq "true")
{
print "it worked";
}else{
print "it did not";
}
If you are just trying to block spam, I prefer the honeypot captcha approach: http://haacked.com/archive/2007/09/10/honeypot-captcha.aspx
Put an input field on your form that should be left blank, then hide it with CSS (preferably in an external CSS file). A robot will find it and will put spam in it but humans wont see it.
In your form validation script, check the length of the field, if it contains any characters, do not process the form submission.

How to capitalize $2 in preg_replace?

I run a community site (built by hand using html, css, and php) for my wow guild. Recently, my members have demanded the ability to use tags like #username in their posts, which would then link to the users page. I already have this script, as listed below:
<?php
$string = '#user really?';
if (preg_match('/(^|\s)#([a-z0-9_]+)/i', $string))
{
$string = preg_replace('/(^|\s)#([a-z0-9_]+)/i', '#$2', $string);
echo $string;
}
else {
echo $string;
}
?>
This works fine, and I notice that the $2 is the user's name, but, since all user's names start with capital letters, the $2 needs to be capitalized, and not everyone does that. Is there a way to code it to automatically capitalize $2, or should I just tell users to remember to capitalize?
Thanx in advance,
Steven
use ucfirst ($2) to capitalize the first character
and strtoupper($2) if you want it all capital
I added more preg_replace and it now links to user no matter how u type name, as long as u have # symbol (#user, #USER, #User, #uSER, etc...). for anyone needing my solution, I will post it below:
<?php
$proper_str = "going to battle with #ADROK";
$proper_str = ucfirst(strtolower($proper_str));
$proper_str = preg_replace('/#[a-z]/e', 'ucfirst(strtoupper("$0"))', $proper_str);
$proper_str = preg_replace('/(^|\s)#([a-z0-9_]+)/i', ' #$2', $proper_str);
echo $proper_str;
?>
and if you change somethings around and make it:
<?php
$proper_str = "going to battle with e#mail.com";
if (preg_match('/(^|\s)#([a-z0-9_]+)/i', $proper_str))
{
$proper_str = ucfirst(strtolower($proper_str));
$proper_str = preg_replace('/#[a-z]/e', 'ucfirst(strtoupper("$0"))', $proper_str);
$proper_str = preg_replace('/(^|\s)#([a-z0-9_]+)/i', ' #$2', $proper_str);
echo $proper_str;
} else {
$proper_str = ucfirst("$proper_str");
echo $proper_str;
}
?>
Then it will leave email addresses alone and make sure first letter of post is capitalized!