Find a specific link in text PHP Wordpress - php

The task itself is for the Wordpress widget.
In each post there are links like "https://www.test.com/example/example1/target", and the task is as follows: find the first link in text leading to "https://www.test.com/example/example1/ "and create a variable that takes the value of "target". Is it real to do? If so, how? I will be very grateful for help. Sorry for my English!
UPD:
I've done this (using $company_ticker as a "target")
$patt = '~(https://www.test.com/example/example/)(\S+)~';
$company_ticker = '';
if (preg_match($patt, $post_content, $company_ticker)) {
list( , $url, $company_ticker) = $company_ticker;
}
But I can't get where is the mistake...

Related

php preg_replace reuse of subject

I've got a big problem and hopefully you can help me out...
I'd like to code a plugin. The plugin should search on a website (for example www.example.com/index.php for a specific word for example Number1. Afterwords the word found should be replaced by an hyperlink. The link should guide to an extern website for example www.example2.com/index.php.
According to the current website, the found word should added to the hyperlink. So if the current site is www.example.com/index.php and the found word is Number1, the hyperlink should look like this:
www.example2.com/index.php/Number1
And it shouldn't be always the same hyperlink, but created dynamic by the word this plugin finds.
Beneath is my current code.
I hope someone can help me out. Thanks.
public function onContentPrepare($context, &$row, &$params, $page = 0)
{
$text = $row->text;
$pattern = array();
$pattern[0] = '/Number1/';
$pattern[1] = '/Number2/';
$pattern[2] = '/Number3/';
$Subject = array();
$Subject[2] = 'https://www.example.com/index.php/';
$Subject[1] = '(...)';
$Subject[0] = '(...)';
$row->text = preg_replace($pattern,$subject,$text);
}

How to grab a word from a page

I was wondering how to grab some text from an external page using PHP.
I think that preg_match() can help but I can't get how to use it.
The text in the page is the following:
dragontail-5.7.2.tgz
and I need to grab only
5.7.2
Thank you for helping.
Check this out:
https://regex101.com/r/cF8mS1/1
/([0-9.]+)/gm
Means "Select all the integer characters since they are more than 1, and include the "." as well, and give me all of them, on multiline too. Thank you."
The last thing to do is to delete the last or first character ".", so:
if (preg_match('/([0-9.]+)/gm', $input, $matches)) {
$result = trim($matches[1], '.');
} else {
$result = null;
}

How to create bitly shortened url from user's inputed text?

Begginer here, people. Could anybody suggest any kind of solution? I've an user inputed text.
First of all I check if the text has any urls:
$post = preg_replace('/https?:\/\/[\w\-\.!~?&+\*\'"(),\/]+/','<a class="post_link"
href="$0">$0</a>',$post);
And after that I need to retrieve that url and put as a variable($url) to this function:
$short=make_bitly_url('$url','o_6sgltp5sq4as','R_f5212f1asdads1cee780eed00d2f1bd2fd794f','xml');
And finally, echo both url and user's text. Thanks in advance for ideas and critiques.
I've tried something like that:
$post = preg_replace('/https?:\/\/[\w\-\.!~?&+\*\'"(),\/]+/e',$url,$post){
$shorten = make_bitly_url($url,'o_6sgltpmm5sq4','R_f5212f11cee780ekked00d2f1bd2fd794f','json');
return '<a class="post_link" href="$shorten">$shorten</a>';
};
But even for me it looks some kind of nonsense.
Bitly does have an API available for use. You should check out API Documentation
Here's how to use the bit.ly API from PHP:
/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
/* usage */
$short = make_bitly_url('http://davidwalsh.name','davidwalshblog','R_96acc320c5c423e4f5192e006ff24980','json');
echo 'The short URL is: '.$short;
// returns: http://bit.ly/11Owun
Source: David Walsh article
HOWEVER, if you wanted to create your own URL shortening system (similar to bit.ly -- and surprisingly easy to do), here is an 8-part tutorial from PHPacademy on how to do that:
Difficulty level: beginner / intermediate
Each video is approx ten minutes.
Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7
Part 8

Using text from a file to point to another file to read

Note: I'm sorry if the title was a little unclear couldn't think of another way to put it.
I am making a PHP posting system for a blog like website. I have a file called posts.txt which has information that points to other text files. These other text files have the physical post content in them. I know this is not the best way to do it but for now this is what I'm doing.
A sample of the posts.txt:
posts/topDownShooter.txt
posts/leapMotionSandbox.txt
end
The first two lines point to other text files that contain post content. The last line "end" lets the program know that all the post "pointers" are done
Here is a sample of a post like topDownShooter.txt
programming
Top Down Shooter
The actual post content goes here
end
The first line is a tag for organization. The second line is the title of the post. And the third is the actual content. The last line serves the same purpose.
Here is my PHP code:
I use "<--" for comments
<?php
$posts = "posts/posts.txt"; <--Pointer to the location of the posts.txt
$postsLines = file($posts);
$fetchingPost = TRUE; <--For while loop
$postNumber = 0;
$postPointer; <--In the example of posts.txt this would be the second or third line
$postTag;
$postTitle;
$postContent;
$endCondition = "end";
while ($fetchingPost == TRUE) {
$endOfFile = strcmp($postsLines[$postNumber], $endCondition);
if ($endOfFile == 0) {
$fetchingPost = FALSE;
}
if ($endOfFile <> 0) {
$postPointer[$postNumber] = $postsLines[$postNumber];
$postTag[$postNumber] = file($postPointer[$postNumber]); <--The problem, see below
$postNumber = $postNumber + 1;
}
}
?>
The Problem: It will not let me use a line that I take out of posts.txt as a "pointer" for accessing topDownShooter.txt or anything like that. I thought that the value I was pulling out of posts.txt was a string but it is not. Is there anyway that I can convert this to a string or make it work?
EDIT:
in short:
is there anyway to take something from $postsLines = file("somerandomtxtfile.txt); and make %postsLines[0] a string?
I'm not sure if I understand your question, but I'd try replacing the line by this
$postTag[$postNumber] = file_get_contents($postPointer[$postNumber]);
Answering the question in your edit, you can do that like this:
$postLines = explode(PHP_EOL, file_get_contents("somerandomtxtfile.txt"));

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Categories