Extracting link from a href and putting it within brackets - php

I have searched and couldn't find what I was looking for.
This is how it will normally be:
<p>
Hi how are you? Have you checked Google or YouTube?
</p>
But what I would love to have, because I'm willing to apply this on a print or PDF page is the following:
<p>
Hi how are you? Have you checked Google (http://www.google.com)
or YouTube (http://www.youtube.com)?
</p>
Now, I understand that there should be some work with regex, but I don't know how to use that. The text will be taken from the variable $content which has the article in it, and what I would like to have is that all links within $content remain as they are plus the content of href be as an additional hyperlink within brackets "()" so that, hypothetically when someone reads a printed article where hyperlinks are they would be able to see the actual URL.

Use a pseudo element to add the href after your links, something like:
a[href]:after
{
content: " (" attr(href) ") ";
}

Here is a handy little Function that may suffice.
<?php
/**#var string $strInput THE STRING TO BE FILTERED */
function doubleUpOnURL($strInput){
$arrAnchorSplit = preg_split("#<\/a>#", $strInput);
$strOutput = "";
$anchorRegX = '(<a\s*href=[\'\"])(.+)([\'\"]>)(.*)';
foreach($arrAnchorSplit as $anchoredString){
$strOutput .= preg_replace("#" . $anchorRegX . "#si" , "$1$2$3$4</a> ($1$2$3$2</a>)", $anchoredString);
}
return $strOutput;
}
$strInput = '<p>Hi how are you? Have you checked Google or YouTube?</p>';
echo(doubleUpOnURL($strInput));
//OUTPUTS:
// Hi how are you? Have you checked Google (http://www.google.com) or YouTube (http://www.youtube.com)?
I hope you find it helpful...

Related

parsing html page using php to find out text on which link is assiged

say i have html code like this
$html = "This is some stuff right here. OH MY GOSH";
i am trying to get values of href and also on which anchor work i mean check this out text i am able to get href value by following this code
$displaybody->find('a ') as $element;
echo $element;
well it works for me but how do i get value of check this out could you guys help me out. i did search but i am not able to find it out . thanks in advance
my actual html look like this
» Download MP4 « - <b>144p (Video Only)</b> - <span> 19.1</span> MB<br />
my href look like this above code return download mp4 and i want it like downloadmp4 114p (video only) 19.1 mb how do i do that
If what you are using now is the SimpleHTMLDOM, then ->innertext works fine on that anchor elements that you have found:
include 'simple_html_dom.php';
$html = "This is some stuff right here. OH MY GOSH";
$displaybody = str_get_html($html);
foreach($displaybody->find('a ') as $element) {
echo $element->innertext . '<br/>';
}
If you were referring to PHP's DOMDocument, then its not find() function you need to use, to target each anchor element, you need to use ->getElementsByTagName(), then each selected elements you need to use ->nodeValue:
$html = "This is some stuff right here. OH MY GOSH";
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('a') as $element) {
echo $element->nodeValue . '<br/>';
}

How to get a url from a database

So I have three pages one that is the index page. One that writes the data from a form inside the index page to the database. And one that gets data from the database and echos out a html table with the data inside.
Currently if you write a link in the form. It will just come out as text. I would like the whole link to be like [link].
so say if I wrote this onto the form:
Look at this: www.google.com or Look at this: https://www.google.com
it would come out like this in html
Look at this: www.google.com
How could I go about doing this?
Okay so the html is:
<form class="wide" action="Write-to.php" method="post">
<input class="wide" autocomplete="off" name="txt" type="text" id="usermsg" style="font-size:2.4vw;" value="" />
</form>
in which the user would write:
"Look at this: www.google.com or Look at this: https://www.google.com"
This would then get sent to the database through Write-to.php.
$sql="INSERT INTO social (comunicate)
VALUES
('$_POST[txt]')";
}
this then gets written back into the database:
$result = mysqli_query($con,"(select * from social order by id desc limit {$limit_amt}) order by id asc");
while($row = mysqli_fetch_array($result))
{
echo "<tr div id='".$i."' class='border_bottom'>";
echo "<th scope='col'>";
echo "<span class='text'>".htmlspecialchars($row['comunicate'])."</span><br />";
echo "</th>";
echo "</tr>";
}
Just try:
echo(''.$your_url_variable.'');
Update:
The OP really wanted to detect url's in a string. One possible solution could be filter it using a regular expression. This code could help:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
Source: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
There are quite a few things you need to worry about when displaying user supplied (tainted) data.
You must ensure that all the data is sanitised -- never ever just echo the content, look into htmspecialchars and FILTER_VALIDATE_URL for example:
function validateUrl($url) {
return filter_var($url, FILTER_VALIDATE_URL);
}
What you are attempting to do is convert a string into a link, for example you can write a function like this:
function makeClickable($link) {
$link = htmlspecialchars($link);
return sprintf('%s', $link, $link);
}
You can use string concatenation as well, but I wouldn't do that in my view code. Just personal preference.
Take a look at the urlencode function, it will certainly come in handy.
I would also recommend you read about cross site scripting
Please note that I am not making any implementation recommendations, my aim is just to show you some contrived code samples that demonstrate making a string "clickable".
Update:
If you would like to make links clickable within text, refer to the following questions:
Best way to make links clickable in block of text
Replace URLs in text with HTML links
save the hyperlink in db and retrieve as a string by sql query
like:
select link from table_name where index = i
and save link as: whaatever here
and print it
Use this
echo '' . $res['url'] . '';

php - get the source of an image

I need to get all the source values from all image inside a container. I'm having some difficulty with this.
Allow me to explain the process.
All the data comes from a database. Inside the backofficce the user enter all the text and the image inside a textarea. To separate the text with the image the user must enter a pagebreak.
Let's go to the code
while ($rowClients = mysql_fetch_array($rsClients)) {
$result = $rowClients['content'];
$resultExplode = explode('<!-- pagebreak -->', $result);
// with resultExplode[0] I get the code and with resultExplde[1] I get the image
// Now with I want to get only the src value from resultExplode[1]
I already tried with strip_tags
$imageSrc = strip_tags($resultadoExplode[1]);
but it doesn't print anything.
I found this post but without success. I stopped in the first print_r.
Can anyone help me??
Thanks
try foreach, if you can't print it out.. (if that's the problem)
foreach($resultExplode as $key => $value){
echo "[".$key."]".$value;
}
I found a solution:
continuing with the previous code I worked with the split function.
So I start to strip the tags. This way I get the img isolated from the rest.
$image = strip_tags($resultExplode[1],"<img>");
Because all the img has the same structure like this: <img width="111" height="28" alt="alternative text" src="/path/to/the/file.png" title="title of the image">
I split this string, using " as a delimiter
$imgSplit = split('"', $image);
$src = $imgSplit[3];
Voilá. It's working
What do you say about this procedeure??

Tag stripping allowing some html tags - Facebook-ish

I am doing something like posting function in a local app it's working fine really but it lacks with validation and not to mention the validation I made was a mess. I'm using jQuery oEmbed.
What I wanted is to print the illegal html tag(s) as is and activate/perform(I don't know the right term) the html tags I have allowed.
Any suggestions?
This is the best solution i came up.
First replaced all the < and > for html code then replaced back the allowed tags.
<?php
$original_str = "<html><b>test</b><strong>teste</strong></html>";
$allowed_tags = array("b", "strong");
$sans_tags = str_replace(array("<", ">"), array("<",">"), $original_str);
$regex = sprintf("~<(/)?(%s)>~", implode("|",$allowed_tags));
$with_allowed = preg_replace($regex, "<\\1\\2>", $sans_tags);
echo $with_allowed;
echo "\n";
Result:
guax#trantor:~$ php teste.php
<html><b>test</b><strong>teste</strong></html&gt
I wonder if there's any solution for replacing all at once. But it works.

Highlight Search Terms in PHP without breaking anchor tags using regex

I'm searching through some database search results on a website & trying to highlight the term in the returned results that matches the searched term. Below is what I have so far (in php):
$highlight = trim($highlight);
if(preg_match('|\b(' . $highlight . ')\b|i', $str_content))
{
$str_content = preg_replace('|\b(' . $highlight. ')(?!["\'])|i', "<span class=\"highlight\">$1</span>",
$str_break;
}
The downside of going this route is that if my search term shows up in the url permalink as well, the returned result will insert the span into the href attribute and break the anchor tag. Is there anyway in my regex to exclude "any" information from the search results that appear in between an opening and closing HTML tag?
I know I could use the strip_tags() function and just spit out the results in plain text, but I'd rather not do that if I didn't have to.
DO NOT try to parse HTML with regular expressions:
RegEx match open tags except XHTML self-contained tags
Try something like PHP Simple HTML DOM.
<?php
// get DOM
$html = file_get_html('http://www.google.com/search?q=hello+kitty');
// ensure this is properly sanitized.
$term = trim($term);
// highlight $term in all <div class="result">...</div> elements
foreach($html->find('div.result') as $e){
echo str_replace($term, '<span class="highlight">'.$term.'</span>', $e->plaintext);
}
?>
Note: this is not an exact solution because I don't know what your HTML looks like, but this should put you pretty close to being on track.
I think assertions is what your looking for.
I ended up going this route, which so far, works well for this specific situation.
<?php
if(preg_match('|\b(' . $term . ')\b|i', $str_content))
{
$str_content = strip_tags($str_content);
$str_content = preg_replace('|\b(' . $term . ')(?!["\'])|i', "<span class=\"highlight\">$1</span>", $str_content);
$str_content = preg_replace('|\n[^<]+|', '</p><p>', $str_content);
break;
}
?>
It's still html encoded, but it's easier to parse through now without html tags

Categories