How to change the href (url) in a link (a) element? - php

Here is my full link.
Client Portal
I want above link to look like following.
Client Portal
I really don't know how to work with preg_replace to get this done.
preg_replace('\/localhost\/mysite\/client-portal\/', '#popup', $output)

If is only this link you can achieve your goal with str_replace():
<?php
$link = 'Client Portal';
$href = 'http://localhost/mysite/client-portal/';
$new_href = '#popup';
$new_link = str_replace($href, $new_href, $link);
echo $new_link;
?>
Output:
Client Portal
If you want you can use DOM:
<?php
$link = 'Client Portal';
$new_href = '#popup';
$doc = new DOMDocument;
$doc->loadHTML($link);
foreach ($doc->getElementsByTagName('a') as $link) {
$link->setAttribute('href', $new_href);
}
echo $doc->saveHTML();
?>
Output:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>Client Portal</body></html>
Or you can use preg_replace() like this:
<?php
$link = 'Client Portal';
$new_href = '#popup';
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "(localhost)"; // Host or IP
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$pattern = "/$regex/";
$newContent = preg_replace($pattern, $new_href, $link);
echo $newContent;
?>
Output:
Client Portal

If you want you can do using jQuery also.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a class="popupClass" href="http://localhost/mysite/client-portal/">Client Portal</a>
$(document).ready(function(){
$('.popupClass').attr('href','').attr('href','#popup');
});
Demo

Related

PHP regex to exactly obtain a string I want

I have a code for embedding a link for iframe.
$post_contetn = explode('htt',$content);
$content_with_link = $post_contetn[0];
$link = 'htt'.$post_contetn[1];
But the problem is that, if I write
http://www.espn.com was great
then it links "was great" is part of the $link.
How can I change (perhaps use regex) to only include the actual url?
======
If I incorporate siam's answer, should it be
$regex = '/https?:\/\/.*?(?=\s)/';
$post_contetn = preg_match($regex, $content, $linkarray);
$content_with_link = $post_contetn[0];
$link = $linkarray[0]
echo $content_with_link;
I then edited to
preg_match($regex, $content, $post_contetn);
$content_with_link = $post_contetn[0];
$link = $post_contetn[0]
echo $content_with_link;
But the error still occurs at echo line.
Try using the following regex :
(?:https?:\/\/\S+)?\S+\.\S+\.?\S+
see demo / explanation
PHP
<?php
$content = 'http://www.espn.com was great';
$regex = '/(?:https?:\/\/\S+)?\S+\.\S+\.?\S+/';
preg_match($regex, $content, $post_contetn);
$link = $post_contetn[0];
echo $link;
?>

Add canonical tag in <head> tag if not existing using PHP

What I want is add canonical tag inside the <head> tag if canonical tag does not exist using PHP
I have tried this but it didn't work
function addtag(){
$doc = new DOMDocument();
$doc->loadHTMLFile('http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
$body = $doc->getElementsByTagName('head')->item(0);
$link = $doc->createElement('link');
$newLink = $body->appendChild($link);
$newLink->setAttribute("canonical", 'http://');
//$linkText = $doc->createTextNode("Display Text For Link");
//$newLink->appendChild($linkText);
echo $doc->saveHTML();
}

How to match and add a class name using preg_replace?

I'm trying to match the class attribute of <html> tag and to add a class name using preg_replace().
Here is what I tried so far:
$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/< *html[^>]*class *= *["\']?([^"\']*)/i';
if(preg_match($pattern, $content, $matches)){
$content = preg_replace($pattern, '<html class="$1 my-custom-class">', $content);
}
echo htmlentities($content);
But, I got only this returned:
<!DOCTYPE html><html class="dummy my-custom-class">"><head></head><body></body></html>
The attribute lang="en" is dropped out and the tag is appended with the duplicates like ">">. Please help me.
Please try this code it works, perfectly well :)
<?php
$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/(<html.*class="([^"]+)"[^>]*>)/i';
$callback_fn = 'process';
$content=preg_replace_callback($pattern, $callback_fn, $content);
function process($matches) {
$matches[1]=str_replace($matches[2],$matches[2]." # My Own Class", $matches[1]);
return $matches[1];
}
echo htmlentities($content);
?>
Remove the * in pattern for regex way
Use this pattern
/<html[^>]*class *= *["\']?([^"\']*)/i
I suggest use Dom parser for parsing the html
<?php
libxml_use_internal_errors(true);
$html="<!DOCTYPE html><html lang='en' class='dummy'><head></head><body></body></html>";
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('html') as $node) {
$node->setAttribute('class','dummy my-custom-class');
}
$html=$dom->saveHTML();
echo $html;
OUTPUT:
<!DOCTYPE html>
<html lang="en" class="dummy my-custom-class"><head></head><body></body></html>

Extract the text from webpage

In this test.php page i have this line of text
server=span.growler.ro&provider=-1&providersSerial=4&country=RO&mobile=0&token=eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb
in this other test1.php?id=token page i have this php code runing
<?php
$Text=file_get_contents("./test.php");
if(isset($_GET["id"])){ $id = $_GET["id"];
$regex = "/".$id."=\'([^\']+)\'/";
preg_match_all($regex,$Text,$Match);
$fid=$Match[1][0];
echo $fid; } else { echo ""; } ?>
i need only the token
eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb
to be show on test1.php?id=token
if in test.php the token looks like this
token='eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb'
it works.
i needet to work from onother web page
$str = 'server=span.growler.ro&provider=-1&providersSerial=4&country=RO&mobile=0&token=eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb';
parse_str($str, $vars);
$token = $vars['token'];
using with preg_match will help you .
$string ='server=span.growler.ro&provider=-1&providersSerial=4&country=RO&mobile=0&token=eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb';
preg_match('/token=([a-f0-9]+)/i',$string,$matches);
echo $matches[1];
this will return you :
'eae5b2c50c123425d9351d8c8ee80b9a27ca3d69f15a669454b937eb'
I'd recommend you to use preg_match instead of preg_match_all
Try this regex:
$regex = "/&?token=([a-f0-9]*)&?/;

PHP regex in simple_html_dom library

I was trying to scrape imdb by following code.
$url = "http://www.imdb.com/search/title?languages=en|1&explore=year";
$html = new simple_html_dom();
$html->load(str_replace(' ','',$data = get_data($url)));
foreach($html->find('#left') as $total_movies)
{
$content = $total_movies->plaintext;
if(preg_match("/(?<total>[0-9,]+) titles/",$content,$matches))
{
print_r($matches);
}
echo $content."<br>";
}
get_data() is just a curl function i created.
The problem is that preg_match is not working. i don't know why but the same thing when used work here. $content contains the text what i scrape in above code.
$content = "1-50 of 101 titles.";
if(preg_match("/(?<total>[0-9,]+) titles/",$content,$matches))
print_r($matches);
The source on the site is actually:
<div id="left">
1-50 of 564,592
titles.
</div>
notice the \n this would need stripping out or added to your condition.
Heres a method to reach your goal without using any added extra library.
<?php
$url = "http://www.imdb.com/search/title?languages=en|1&explore=year";
$temp=file_get_contents($url);
$xml = new DOMDocument();
#$xml->loadHTML($temp);
foreach($xml->getElementsByTagName('div') as $div) {
if($div->getAttribute('id')=='left'){
preg_match("#of ([0-9,]+)#",$div->nodeValue,$match);
$matchs[]=preg_replace('/[^0-9]/', '', $match[0]);
}
}
echo number_format($matchs[0]); //564,592
?>

Categories