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;
}
Related
Ok so here is what I am trying to do, I need a php function that I can pass 4 parameters.
1) A String (Containing Tokens with text between them)
2) A Start Token String Parameter
3) A Stop Token String Parameter
4) A DO NOT DELETE String Parameter
I want to pass a (1)long string to the function and have it remove all the multiple instances of the (2)Start Tokens and all the Text Until The (3)Stop Token, UNLESS the (4)Do NOT DELETE Parameter is present in that part of the String.
The Setup would be like this:
HERE is the way the function would be setup:
function CleanUpMyString($string-1, $start-2, $end-3, $keep-4){
// Working Code That Does The Work Here
}
The String That I could Pass To The Function May Look Like this examples:
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
Assuming I called the function like this:
echo CleanUpMyString($stringTEST, '<<<', '>>>', 'keep>');
I would get the following output:
This is the intro of the string, in the next snippet of the string, This is going pretty well. We do not delete this part because of the added token part 'keep>'. We will add some more rambling text here. Then we will add another snippet. But in the end it is all good!
I have no control over the input string, so the tokens could occur anywhere in any number, and there is not rational order in which they may appear.
I really am not sure where to start. I took a look at this thread:
PHP function to delete all between certain character(s) in string
which I thought has been the closest thing to what I wanted, but I could not see how to extend the idea to my application. Any help would be seriously appreciated!
my suggestion is to use preg_replace_callback
<?php
function CleanUpMyString($string, $start, $end, $keep)
{
return preg_replace_callback(
'~' . preg_quote($start, '~') . '.+?' . preg_quote($end, '~') . '~',
function ($M) use ($start, $end, $keep) {
if (strpos($M[0], $keep)) {
return str_replace([$start, $end, $keep], '', $M[0]);
} else {
return '';
}
},
$string
);
}
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
echo CleanUpMyString($stringTEST, '<<<', '>>>', 'keep>');
Hope this will help you out, Here i am using preg_match to gather all matching tokens from start to end and then we are iterating over matches to keep required portion of string and removing un-necessary part.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
echo CleanUpMyString($stringTEST, "<<<", ">>>", "keep>");
function CleanUpMyString($stringTEST, $start, $end, $keep)
{
$startQuotes= preg_quote($start);
$endQuotes= preg_quote($end);
preg_match_all("/$startQuotes.*?(?:$endQuotes)/", $stringTEST,$matches);
foreach($matches[0] as $key => $value)
{
if(stristr($value, $start.$keep)!==false)
{
$stringTEST= substr_replace($stringTEST,"",strpos($stringTEST, $start.$keep), strlen($start.$keep));;
$stringTEST= substr_replace($stringTEST,"",strpos($stringTEST, $end), strlen($end));
}
else
{
$stringTEST= str_replace($value, "", $stringTEST);
}
}
return $stringTEST;
}
I want PHP read my article text file like this.
sample text file :
OMG! Where is my right hand.
I try to find my right hand but I can't see it.
please tell me how to find it.
Now I have this function code
function getContent($file_path,$path=''){
$file_path = $file_path;
if(file_exists('./'.$file_path)){
$f_read = fopen($path.$file_path,'r');
$rs = "";
while (!feof($f_read)) {
$rs .= fread($f_read, 8192);
}
fclose($f_read);
}
else{
echo $rs = "Not Connect File !";
}
return($rs);
}
after use that code :
OMG! Where is my right hand. I try to find my right hand but I can't see it. please tell me how to find it.
I want to use PHP function read first line to string1 and after first line is string2 like this
$string1 = "OMG! Where is my right hand."
$string2 = "I try to find my right hand but I can't see it.
please tell me how to find it."
Help me please :)
You can use below code for splitting your paragraph into string and also assign the character (like period, comma, etc.) from where do you want the paragraph to split.
preg_split('/[.?!]/',$mystring);
You may refer this link for more information: Explode a paragraph into sentences in PHP
or
http://php.net/manual/en/function.explode.php
You can use $string=#file_get_contents($path_name); $string=#explode("\n",$string); //for get each line.
In order to to read the first line into $string1 and the rest of the file into $string2 ...
Read the first line, as you do above, then call file_get_contents to get the rest.
Use the offset parameter to tell file_get_contents() to start reading after the end of the first line (pass the string length of the first line).
try using explode() function of PHP
function getContent($file_path,$path=''){
$file_path = $file_path;
if(file_exists('./'.$file_path)){
$f_read = fopen($path.$file_path,'r');
$rs = "";
while (!feof($f_read)) {
$rs .= fread($f_read, 8192);
$demo=explode('.', $rs);
}
fclose($f_read);
}
else{
echo $rs = "Not Connect File !";
}
return($demo);//result wiil be stored in $demo array like $demo[0], $demo[1]
}
I am trying to create file links based a variable which has a "prefix" and an extension at the end.
Here's what I have:
$url = "http://www.example.com/mods/" . ereg("^[A-Za-z_\-]+$", $title) . ".php";
Example output of what I wish to have outputted (assuming $title = testing;):
http://www.example.com/mods/testing.php
What it currently outputs:
http://www.example.com/mods/.php
Thanks in advance!
Perhaps this is what you need:
$title = "testing";
if(preg_match("/^[A-Za-z_\-]+$/", $title, $match)){
$url = "http://www.example.com/mods/".$match[0].".php";
}
else{
// Think of something to do here...
}
Now $url is http://www.example.com/mods/testing.php.
Do you want to keep letters and remove all other chars in the URL?
In this case the following should work:
$title = ...
$fixedtitle=preg_replace("/[^A-Za-z_-]/", "", $title);
$url = "http://www.example.com/mods/".$fixedtitle.".php";
the inverted character class will remove everything you do not want.
OK first it's important for you to realize that ereg() is deprecated and will eventually not be available as a command for php, so to prevent an error down the road you should use preg_match instead.
Secondly, both ereg() and preg_match output the status of the match, not the match itself. So
ereg("^[A-Za-z_\-]+$", $title)
will output an integer equal to the length of the string in $title, 0 if there's no match and 1 if there's a match but you didn't pass it another variable to store the matches in.
I'm not sure why it's displaying
http://www.example.com/mods/.php
It should actually be outputting
http://www.example.com/mods/1.php
if everything was working correctly. So there is something going on there, and it's definitely not doing what you want it to. You need to pass another variable to the function that will store all the matches found. If the match is successful (which you can check using the return value of the function) then that variable will be an array of all matches.
Note that with preg_match by default only the first match will be returned. but it will still generate an array (which can be used to get isolated portions of the match) whereas preg_match_all will match multiple things.
See http://www.php.net/manual/en/function.preg-match.php for more details.
Your regex looks more or less correct
So the proper code should look something like:
$title = 'testing'; //making sure that $title is what we think it is
if (preg_match('/^[A-Za-z_\-]+$/',$title,$matches)) {
$url = "http://www.example.com/mods/" . $matches[0] . ".php";
} else {
//match failed, put error code in here
}
Do I do something wrong?
I need the youtube code, but it doesn't return the real value.
if(preg_match_all("http:\/\/www\.youtube\.com\/v\/(.*)(.*)", $row->n_texto, $matches){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}
Edit - ircmaxell Based on the comment, the link structure in the text is:
http:// www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0
Update
The problem is: my code return a link like this:
http://www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0
Can I stop it with regexp before appear %26hl=en%26fs=1%26rel=0?
Your regex is not correct. There are more than a few things wrong with it. Now, as far as what you want, try this:
#http://(?:.*)youtube.com/v/([^/\#?]+)#
Now, as for why, let's look at the regex:
http://(?:.*)youtube.com
You're looking for a string that starts with http://, has anything after (www., ww2., or nothing).
/v/
You're looking for /v/ as the start of the URL.
([^/\\#?]+)
You're looking for everything else UP TO another /, a query string (?) or a anchor (#). So that should match the ID you're looking for.
So, it would be
if(preg_match("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1]."/0.jpg";
}
If you wanted to find all:
if(preg_match_all("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
foreach ($matches[1] as $match) {
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$match."/0.jpg";
}
}
the link provided has a space before the 1st w in www.youtube.com, the code you need is :
if(preg_match_all("%http://www\.youtube\.com/v/([\w]+)%i", $row->n_texto , $matches)){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}
also, the url you have is encoded, you may want to use urldecode($row->n_texto) before using it.
^http://\w{0,3}.?youtube+\.\w{2,3}/watch\?v=[\w-]{11}
according to http://www.regexlib.com/REDetails.aspx?regexp_id=2569
Okay so i set up this thing so that I can print out page that people came from, and then put dummy tags on certain pages. Some pages have commented out "linkto" tags with text in between them.
My problem is that some of my pages don't have "linkto" text. When I link to this page from there I want it to grab everything between "title" and "/title". How can I change the eregi so that if it turns up empty, it should then grab the title?
Here is what I have so far, I know I just need some kind of if/then but I'm a rank beginner. Thank you in advance for any help:
<?php
$filesource = $_SERVER['HTTP_REFERER'];
$a = fopen($filesource,"r"); //fopen("html_file.html","r");
$string = fread($a,1024);
?>
<?php
if (eregi("<linkto>(.*)</linkto>", $string, $out)) {
$outdata = $out[1];
}
//echo $outdata;
$outdatapart = explode( " " , $outdata);
echo $part[0];
?>
Here you go: if eregi() fails to match, the $outdata assignment will never happen as the if block will not be executed. If it matches, but there's nothing between the tags, $outdata will be assigned an empty string. In both cases, !$outdata will be true, so we can fallback to a second match on the title tag instead.
if(eregi("<linkto>(.*?)</linkto>", $string, $link_match)) {
$outdata = $link_match[1];
}
if(!$outdata && eregi("<title>(.*?)</title>", $string, $title_match)) {
$outdata = $title_match[1];
}
I also changed the (.*) in the match to (.*?). This means, don't be greedy. In the (.*) form, if you had $string set to
<title>Page Title</title> ...
... <iframe><title>A second title tag!</title></iframe>
The regex would match
Page Title</title> ... ... <iframe><title>A second title tag!
Because it tries to match as much as possible, as long as the text is between any and any other !. In the (.*?) form, the match does what you'd expect - it matches
Page Title
And stops as soon as it is able.
...
As an aside, this thing is an interesting scheme, but why do you need it? Pages can link to other pages and pass parameters via the query string:
...
Then somescript.php can access the prevpage parameter via the $_GET['prevpage'] superglobal variable.
Would that solve your problem?
The POSIX regex extension (ereg etc.) will be deprecated as of PHP 5.3.0 and may be gone completely come PHP 6, you're better off using the PCRE functions (preg_match and friends).
The PCRE functions are also faster, binary safe and support more features like non-greedy matching etc.
Just a pointer.
you need if, else.
if(eregi(...))
{
.
.
.
}
else
{
just grab title;
}
perhaps you should have done a quick google search to find this very simple answer.
Just add another if test before you assign the match to $outdata:
if (eregi("<linkto>(.*)</linkto>", $string, $out)) {
if ($out[1] != "") {
$outdata = $out[1];
} else {
// Look in the title.
}
}