How to capitalize $2 in preg_replace? - tags

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!

Related

Formmail - make it show name and email in success response

I'm using formmail.pl to handle a form I'm using on my site. There are several fields which are sent to the script including name, email, phone and some text in a text area.
As it stands, the successful submission prints the phone and textarea data correctly but doesn't print the name and email which were entered. In the email it sends the name and email in the 'from' header and as with the success page only shows the phone and textarea data are shown in the email body.
I would like to show all data in both cases however I can't seem to find the section of code that handles this. I'd post up the formmail.pl script except its over 3000 lines of code so I'll just post the places I think are responsible and hopefully somebody can point me in the right direction. I'm fairly new to Perl and its a bit overwhelming reading and understanding a script of this size.
sub success_page {
my ($self, $date) = #_;
if ($self->{FormConfig}{'redirect'}) {
print $self->cgi_object->redirect( $self->{FormConfig}{'redirect'} );
}
elsif ( $self->{CFG}{'no_content'}) {
print $self->cgi_object->header(Status => 204);
}
else {
$self->output_cgi_html_header;
$self->success_page_html_preamble($date);
$self->success_page_fields;
$self->success_page_footer;
}
}
sub success_page_html_preamble {
my ($self, $date) = #_;
my $title = $self->escape_html( $self->{FormConfig}{'title'} || 'Success' );
my $torecipient = 'to ' . $self->escape_html($self->{FormConfig}{'recipient'});
$torecipient = '' if $self->{Hide_Recipient};
my $attr = $self->body_attributes;
print <<END;
<head>
<title>$title</title>
END
$self->output_style_element;
print <<END;
<link type="text/css" href="css/stylesheet.css" rel="stylesheet" /></script>
</head>
<body>
<p>Below is what you submitted $torecipient on $date</p>
END
}
sub success_page_fields {
my ($self) = #_;
foreach my $f (#{ $self->{Field_Order} }) {
my $val = (defined $self->{Form}{$f} ? $self->{Form}{$f} : '');
$self->success_page_field( $self->escape_html($f), $self->escape_html($val) );
}
}
sub success_page_field {
my ($self, $name, $value) = #_;
print "<p><b>$name:</b> $value</p>\n";
}
Okay that's getting a bit long. That stuff is mostly for the success page and not much to do with the email side of things but maybe if somebody can find what I need there I can apply it to the email section also.
If any further information is needed let me know
Thanks in Advance
I haven't really used NMS FormMail myself, but looking at the source, it seems that you should be able to achieve something like what you want by setting the following extra configuration options:
$more_config{include_config_email} = 1;
$more_config{include_config_realname} = 1;
This should cause FormMail.pl to treat the email and realname fields as normal form fields, in addition to their special meaning.

PHP preg_replace with any variation of upper/lowercase?

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.

Extracting links inside <div>'s with HTML::TokeParser & URI

I'm an old-newbie in Perl, and Im trying to create a subroutine in perl using HTML::TokeParser and URI.
I need to extract ALL valid links enclosed within on div called "zone-extract"
This is my code:
#More perl above here... use strict and other subs
use HTML::TokeParser;
use URI;
sub extract_links_from_response {
my $response = $_[0];
my $base = URI->new( $response->base )->canonical;
# "canonical" returns it in the one "official" tidy form
my $stream = HTML::TokeParser->new( $response->content_ref );
my $page_url = URI->new( $response->request->uri );
print "Extracting links from: $page_url\n";
my($tag, $link_url);
while ( my $div = $stream->get_tag('div') ) {
my $id = $div->get_attr('id');
next unless defined($id) and $id eq 'zone-extract';
while( $tag = $stream->get_tag('a') ) {
next unless defined($link_url = $tag->[1]{'href'});
next if $link_url =~ m/\s/; # If it's got whitespace, it's a bad URL.
next unless length $link_url; # sanity check!
$link_url = URI->new_abs($link_url, $base)->canonical;
next unless $link_url->scheme eq 'http'; # sanity
$link_url->fragment(undef); # chop off any "#foo" part
print $link_url unless $link_url->eq($page_url); # Don't note links to itself!
}
}
return;
}
As you can see, I have 2 loops, first using get_tag 'div' and then look for id = 'zone-extract'. The second loop looks inside this div and retrieve all links (or that was my intention)...
The inner loop works, it extracts all links correctly working standalone, but I think there is some issues inside the first loop, looking for my desired div 'zone-extract'... Im using this post as a reference: How can I find the contents of a div using Perl's HTML modules, if I know a tag inside of it?
But all I have by the moment is this error:
Can't call method "get_attr" on unblessed reference
Some ideas? Help!
My HTML (Note URL_TO_EXTRACT_1 & 2):
<more html above here>
<div class="span-48 last">
<div class="span-37">
<div id="zone-extract" class="...">
<h2 class="genres"><img alt="extracting" class="png"></h2>
<li><a title="Extr 2" href="**URL_TO_EXTRACT_1**">2</a></li>
<li><a title="Con 1" class="sel" href="**URL_TO_EXTRACT_2**">1</a></li>
<li class="first">Pàg</li>
</div>
</div>
</div>
<more stuff from here>
I find that TokeParser is a very crude tool requiring too much code, its fault is that only supports the procedural style of programming.
A better alternatives which require less code due to declarative programming is Web::Query:
use Web::Query 'wq';
my $results = wq($response)->find('div#zone-extract a')->map(sub {
my (undef, $elem_a) = #_;
my $link_url = $elem_a->attr('href');
return unless $link_url && $link_url !~ m/\s/ && …
# Further checks like in the question go here.
return [$link_url => $elem_a->text];
});
Code is untested because there is no example HTML in the question.

weird php error - cannot explain just in title

discovered this forum a few days ago and still not into it enough to contribute - will happen soon i hope :)
right now i am experiencing something weird i hope someone can help me with.
In the following php code:
when i run it and enter a valid username and password, it will always send me to failed.php although it should have returned a result.
When i add a random "echo" before the if clause, it goes into the correct branch, but of course can't do the header("Location..) any more.
Does anyone have an idea what i am missing here or why this is happening?
Could it be some PHP setting i am not aware of?
thanks in advance
Seb
(NOTE i know php4 is not up to date, sql injections etc. - i just want to know and maybe understand why this is happening ;) )
<?php
include("config.php");
$query = 'select * from users where username = "' .
$_POST['username'] . '" and password = "' .
md5($_POST['password']) . '"';
$select_user = mysql_query($query);
//echo "something";
if ($select_user && ($row = mysql_fetch_row($select_user)))
{
$user_id = $row[0];
session_start();
session_register('authorized');
$_SESSION['authorized'] = true;
$_SESSION['uid'] = $user_id;
//echo "anothersomething";
header("Location: portal.php");
exit;
}
else
{
$_SESSION['authorized'] = false;
$_SESSION['uid'] = 0;
header("Location: failed.php");
exit;
}
#MYSQL_CLOSE($db);
?>

Triggering conversion tracking code on form submit

I have a PHP form that mail()s the form data on submit and then if successful returns them to the referring page (in other words keeping them on the same page as the form) and appends ?success=TRUE to the URL.
The question is, how would I implement the AdWords and Yahoo Search Marketing conversion code snippets to trigger only when the form is submitted? For functionality purposes, it is unfortunately not feasible to send them to another page on submit which would have been the easiest way to do it.
The relevant code from the form submit action that mails the results and sends them back to the homepage is below. I have a hunch it might be as simple as outputting the conversion tracking code snippets in the if statement at the end there but I'm not sure if that is correct or the syntax to properly do that.
if ( isset($_POST['sendContactEmail']) )
{
$fname = $_POST['posFName'];
$lname = $_POST['posLName'];
$phone = $_POST['posPhone'];
$email = $_POST['posEmail'];
$note = $_POST['posText'];
$to = $yourEmail;
$subject = $yourSubject;
$message = "From: $fname $lname\n\n Phone: $phone\n\n Email: $email\n\n Note: $note";
$headers = "From: ".cleanPosUrl($_POST['posFName']. " " .$_POST['posLName'])." \r\n";
$headers .= 'To: '.$yourName.' '."\r\n";
$mailit = mail($to,$subject,$message,$headers);
if ( #$mailit ) {
header('Location: '.$referringPage.'?success=true');
}
else {
header('Location: '.$referringPage.'?error=true');
}
}
Outputting it in the if-Statement would be a possibility, but the script you posted adds another way to do it as it redirects to the $referringPage - if the mail was successfully sent. And that's the only event you want to track a conversion.
So edit the code of $referringPage (the page that holds the form fields) and add:
<?php
if($_GET['success'] == 'true') {
echo "...";
}
?>
"..." ofcourse has to be replaced by the Adwords conversion Code Google gave you.
If you add it to your question, I could even add it to my answer.