Why preg_replace() function isn't working properly? - preg-replace

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));

Related

php regex to replace last dot

http://i.imgur.com/KKtAU8X.jpg
preg_replace to change be like
http://i.imgur.com/KKtAU8Xt.jpg
replace last dot to t.
try code
/\.([^.]*)$/ or /(.*)\.([^.]*)$/
add it remove .jpg too!
I need to keep .jpg
$ cat test.php
<?
$url = 'http://i.imgur.com/KKtAU8X.jpg';
$newUrl = preg_replace('#^(.+)\.([\w]+)$#i', '$1t.$2', $url);
var_dump($url, $newUrl);
$ php test.php
string(30) "http://i.imgur.com/KKtAU8X.jpg"
string(31) "http://i.imgur.com/KKtAU8Xt.jpg"

PHP DOMDocument - match and remove URLs

I'm trying to extract links from html page using DOM:
$html = file_get_contents('links.html');
$DOM = new DOMDocument();
$DOM->loadHTML($html);
$a = $DOM->getElementsByTagName('a');
foreach($a as $link){
//echo out the href attribute of the <A> tag.
echo $link->getAttribute('href').'<br/>';
}
Output:
http://dontwantthisdomain.com/dont-want-this-domain-name/
http://dontwantthisdomain2.com/also-dont-want-any-pages-from-this-domain/
http://dontwantthisdomain3.com/dont-want-any-pages-from-this-domain/
http://domain1.com/page-X-on-domain-com.html
http://dontwantthisdomain.com/dont-want-link-from-this-domain-name.html
http://dontwantthisdomain2.com/dont-want-any-pages-from-this-domain/
http://domain.com/page-XZ-on-domain-com.html
http://dontwantthisdomain.com/another-page-from-same-domain-that-i-dont-want-to-be-included/
http://dontwantthisdomain2.com/same-as-above/
http://domain3.com/page-XYZ-on-domain3-com.html
I would like to remove all results matching dontwantthisdomain.com, dontwantthisdomain2.com and dontwantthisdomain3.com so the output will looks like that:
http://domain1.com/page-X-on-domain-com.html
http://domain.com/page-XZ-on-domain-com.html
http://domain3.com/page-XYZ-on-domain3-com.html
Any ideas? :)
I think you should use regular expression.Google it and have fun

PHP - echo inside an echo

I have a PHP if/else statement. This is the code I'm trying to echo under an else condition.
<?php $locked = ForumData::is_topic_locked($post->topic_id);
if ($locked->topic_locked == 1) {echo '<td align="right"><font color="#FF0000">Topic Locked</font><td>';}
else {
echo '<td align="left"><img src="<?php echo SITE_URL?>/lib/skins/flyeuro/images/forums/t_reply.gif"/></td>'; }
?>
The bit I'm interested to echo is this.
<img src="<?php echo SITE_URL?>
If I try this... 'echo SITE_URL'
Parse error: syntax error, unexpected T_ECHO, expecting ',' or ';'
But this doesn't parse the image, and if I try parsing anything else, it's giving me parsing errors, which I can't fix?
How can I therefore produce an echo inside another echo?
why did you open a <?php tag again, you are already in echo line?
echo '<td align="left"><img src="'.SITE_URL.'/lib/skins/flyeuro/images/forums/t_reply.gif"/></td>';
and what is SITE_URL? Is that a variable, did you forget to put $?
echo prints out the string that you gave as parameter,
echo "foo";
As #hakre mentioned about it, . is used to concatenate strings.
$var = "foo"."bar"; //foobar
So you can use it in echo line,
$var = "foo"."bar"; //foobar
echo "foo "."bar ".$var // foo bar foobar
And It's not important weather variable defined as a string. It would be a constant variable.
define('SITE_URL', 'localhost:8080/phpvms');
echo "my website URL is ".SITE_URL; //my website URL is localhost:8080/phpvms
Remember:
<?php echo "View"; ?>
" and \
this!
Hope that's enough of a hint!#
Your problem is probably solved this way:
echo '<td align="left"><a href="',
url('Forum/create_new_post?topic_id=' . $post->topic_id . '&forum_id=' . $post->forum_id . '') ,
'"><img src="', SITE_URL,
#######################
'/lib/skins/flyeuro/images/forums/t_reply.gif"/></a></td>';
In PHP you can use constants quite like variables, e.g. to output them. You don't need to stack echoes inside each other or something.

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.