how to explode a url string? - php

code:
<?php
include('conn.php');
$student_id = $_SESSION['student_id'];
$college_name = $_GET['college_name'];
$college_name22 = explode('(', $college_name);
if(preg_match('#\((.*?)\)#', $college_name, $match))
{
$match[1] = lcfirst($match[1]);
}
else
{
$match[1] = 'All';
}
?>
If url having string like
cstest/view.php?college_name=Agra%20Public%20Institute%20of%20Technology%20&%20Computer%20Education,%20Artoni%20(Pharmacy)
and I want to explode the following string i.e.
Agra%20Public%20Institute%20of%20Technology%20&%20Computer%20Education,%20Artoni%20(Pharmacy)
when I echo $college_name it display only (Agra Public Institute of Technology) not full name i.e (Agra Public Institute of Technology & Computer Education, Artoni) and $match[1] contain (pharmacy) which is not showing when I print $match[1] it show 'All'. So, how can I fix this problem ?
Thank You

The & has a special meaning in URL. the value of $_GET['college_name'] is exactly "Agra%20Public%20Institute%20of%20Technology%20". The & marks the start of a new parameter.
If the ampersand is properly escaped as %26 you will have a much easier time.
You could try inserting a var_dump($_GET) and see what the data is that you are actually working with.

Related

How to get first word of URL parameter

I want to echo only the first word of a url parameter. For example: /?name=Mike%20Jackson. I want only "Mike". How is that done?
I can get the whole parameter.
<?php // show welcome back message if coming from the waiting list email
$name = '';
if (isset($_GET["name"]))
{
$fullname = $_GET["name"];
}
?>
I expect the first word only.
To break the string at a space, you would use the explode function. That separates the parameter and breaks it into an array, so to get the first word you just need to get the 0th index:
$fullname = explode(" ", $_GET["name"])[0];
If space in your URL is encoded as in your example, you just need to replace the space with the encoding:
$fullname = explode("%20", $_GET["name"])[0];
Edit: As pointed out in the comments, the first method should be the way to go because your method of getting the parameter automatically decodes the URL.

Can not get the special charcter from query string value using PHP

I need one help. I need to fetch all data from query string using PHP but some special charcters like (i.e-+,- etc) are not coming. I am explaining my code below.
http://localhost/test/getmethod.php?name=Goro + Gun
Here I need to get the value assign to name using the below code.
<?php
$name=$_GET['name'];
echo $name;
?>
Here I am getting the output like Goro Gun but I need the original value i.e-Goro + Gun .Please help me to resolve this issue.
#subhra try this for this case name=Goro + Gun:
<?php
$nameArr = explode('=', $_SERVER['QUERY_STRING']);
$name = str_replace("%20", " ", $nameArr[1]);
echo $name;
?>
$_SERVER['QUERY_STRING'] - this will return you full query string

Make a function happen while echoing some text if a certain string matches in PHP

I have an array element that contains a subpage's content:
$page['content']
I want to do some MySQL query, if the variable's content contains this pattern: {gallery:somerandomIDnumber}
The problem is, I don't want to lose the other stuff, and it's also important that the query should run where the pattern belongs.
For example, this is the $page['content'] content:
<h1>Title of the page</h1>
{gallery:10}
<p>Other informations...</p>
I tried this with preg_match function, but unfortunately I can't figure it out, how I can save the other content around my {gallery:10} pattern.
// Gallery include by ID
preg_match('~\{gallery\:[0-9]{1,5}\}~', $page['content'], $matches);
foreach($matches[0] as $value) {
$int = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$query = 'SELECT * ';
$query .= 'FROM gallery_images ';
$query .= 'WHERE gid = '.$int;
$gallery = ms_query($query); //ms_query is a function I wrote myself. Unlike mysqli_query function this function doesn't require the connection parameter every single time I call it, only the query itself
while($gimage = mysqli_fetch_assoc($gallery)) {
echo '<img src="admin/uploaded/'.$gimage['imagepath'].'" width ="100">';
}
}
Summarazing, in this situation, I want to echo
the title of the page
some imagepath from my database
other informations
Thanks in return for Your help!
preg match will get you something in $matches only when u put it in ().
e.g. in your {gallery:10}
you will get the 10 if you make your preg like this;
preg_match('~{gallery:([0-9]{1,5})}~', $page['content'], $matches);
also echo your sql query and paste result

if else on variable link input

I have a method of pulling Youtube video data from API links. I use Wordpress and ran into a snag.
In order to pull the thumbnail, views, uploader and video title I need the user to input the 11 character code at the end of watch?v=_______. This is documented with specific instructions for the user, but what if they ignore it and paste the whole url?
// the url 'code' the user should input.
_gXp4hdd2pk
// the wrong way, when the user pastes the whole url.
https://www.youtube.com/watch?v=_gXp4hdd2pk
If the user accidentally pastes the entire URL and not the 11 character code then is there a way I can use PHP to grab either the code or whats at the end of this url (11 characters after 'watch?v='?
Here is my PHP code to pull the data:
// $url is the code at the end of 'watch?v=' that the user inputs
$url = get_post_meta ($post->ID, 'youtube_url', $single = true);
// $code is a variable for placing the $url in a youtube link so I can output it to an API link
$code = 'http://www.youtube.com/watch?v=' . $url;
// $code is called at the end of this oembed code, allowing me to decode json data and pull elements from json to echo in my html
// echoed output returns json file. example: http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=_gXp4hdd2pk
$json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($code));
Im looking for something like...
"if user inputs code, use this block of code, else if user inputs whole url use a different block of code, else throw error."
Or... if they use the whole URL can PHP only use a specific section of that url...?
EDIT: Thank you for all the answers! I am new to PHP, so thank you all for your patience. It is difficult for graphic designers to learn PHP, even reading the PHP manual can give us headaches. All of your answers were great and the ones ive tested have worked. Thank you so much :)
Try this,
$code = 'https://www.youtube.com/watch?v=_gXp4hdd2pk';
if (filter_var($code, FILTER_VALIDATE_URL) == TRUE) {
// if `$code` is valid url
$code_arr = explode('?v=', $code);
$query_str = explode('&', $code_arr[1]);
$new_code = $query_str[0];
} else {
// if `$code` is not a valid url like '_gXp4hdd2pk'
$new_code = $code;
}
echo $new_code;
Here's a simple option for you to do, unless you want to use regex like Nisse Engström's Answer.
Using the function parse_url() you could do something like this:
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
now $video_id would return:
_gXp4hdd2pk
from the $url supplied in the above code.
I suggest you read the parse_url() documentation to ensure you understand and grasp it all :-)
Update
for your comment.
You'd use something like this to make sure the parsed value is a valid URL:
// this will check if valid url
if (filter_var($code, FILTER_VALIDATE_URL)) {
// its valid as it returned true
// so run the code
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
} else {
// they must have posted the video code as the if check returned false.
$video_id = $url;
}
Just try as follows ..
$url =" https://www.youtube.com/watch?v=_gXp4hdd2pk";
$url= explode('?v=', $url);
$endofurl = end($url);
echo $endofurl;
Replace $url variable with input .
I instruct my users to copy and paste the whole youtube url.
Then, I do this:
$video_url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk'; // this is from user input
$parsed_url = parse_url($video_url);
parse_str($parsed_url['query'], $query);
$vidID = isset($query['v']) ? $query['v'] : NULL;
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID; // this is used for the Api
$m = array();
if (preg_match ('#^(https?://www.youtube.com/watch\\?v=)?(.+)$#', $url, $m)) {
$code = $m[2];
} else {
/* No match */
}
The code uses a Regular Expression to match the user input (the subject) against a pattern. The pattern is enclosed in a pair of delimiters (#) of your choice. The rest of the pattern works like this:
^ matches the beginning of the string.
(...) creates a subpattern.
? matches 0 or 1 of the preceeding character or subpattern.
https? matches "http" or "https".
\? matches "?".
(.+) matches 1 or more arbitrary charactes. The . matches any character (except newline). + matches 1 or more of the preceeding character or subpattern.
$ matches the end of the string.
In other words, optionally match an http or https base URL, followed by the video code.
The matches are then written to $m. $m[0] contains the entire string, $m[1] contains the first subpattern (base URL) and $m[2] contains the second subpattern (code).

Create URL with only A-Z characters that includes variable and extension

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
}

Categories