How to get Implode get data before this string? - php

My url is
likehttp://localhost/manishatutors/tutors-in-city/Crossing-Republik-tutor/
how could i get Crossing Republic
using php
I used
<?php
list($a,$page_get) = explode("city/",$_SERVER['REQUEST_URI']);
$array=explode("/",$page_get);
$getCity1=remove_dash($array[0]);
$p=$array[1];
$get_city = implode('-',$getCity1);
print_r($get_city);
?>
but its giving
Crossing republik tutor
while I don't want tutor

use explode function and take the last
$req_uris = explode('/',$_SERVER['REQUEST_URI']);
echo $req_uris[count($req_uris)-1];
and if you want you can replace dash with space
echo str_replace('-', ' ', $req_uris[count($req_uris)-1]);
EDIT
$url = 'http://localhost/manishatutors/tutors-in-city/Crossing-Republik-tutor/';
$exploded = array_values(array_filter(explode('/',$url)));
$last = $req_uris[count($exploded)-1];
echo str_replace( '-', ' ', str_replace('tutor', '', $last) );
change $url with $_SERVER['REQUEST_URI']

You may try this
<?php
list($a,$val) = explode("city/",$_SERVER['REQUEST_URI']);
$array=explode("/",$val);
$val2=remove_dash($array[0]);
$p=$array[1];
$val3= implode('-',$val2);
print_r($val3);
?>
NEW EDITED ANSWER
list($a,$val) = explode("city/",$_SERVER['REQUEST_URI']);
$array=explode("/",$val);
$val2=$array[0];
$p=$array[1];
$val3= implode('-tutor',$val2);
print_r(remove_dash($val3[0]));
?>

Related

How to get string after second slash in url - using php?

How to get string after second slash in url? URL is different every time (more slashes), but every time I need the whole text after the second slash. How to do it?
I am using this code:
<?php
$str = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$last = substr($str, strrpos($str, '/') - 1);
echo $last;
?>
...but it works online with some characters after slash.
Thank you very much for help.
$last = explode("/", $str, 3);
echo $last[2];
<?php
$str = "google.com/whatever/hello";
$last = GetStringAfterSecondSlashInURL($str);
echo $last;
function GetStringAfterSecondSlashInURL($the_url)
{
$parts = explode("/",$the_url,3);
if(isset($parts[2]))
return $parts[2];
}
?>
use
<?php
$str = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$last = explode("/",$str,3);// so at second index rest of the string will come.
echo $last[2];
see here http://www.w3schools.com/php/func_string_explode.asp

Get number from an url in PHP

I have the following url : http:example.com/country/France/45.
With the pattern http:example.com/country/name/**NUMBER**(?$_GET possibly).
How can I extract the number with a regex (or something else then regex) ?
With regexp:
$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);
$url = 'http:example.com/country/France/45';
$id = end(explode('/',trim($url,'/')));
Simple isn't ?
The usage of trim () is to remove trailing \
echo $last = substr(strrchr($url, "/"), 1 );
strrchr() will give last occurence of the / character and then substr() gives string after it.
use something like this
$url = "http://example.com/country/France/45";
$parts = explode('/', $url);
$number = $parts[count($parts) - 1];
and if you have GET variable at the end, you can explode further like this
$number = explode('?', $number);
$number = $number[0];
hope this helps :)
the get command for php is $_GET so to show to number do
<html>
<body>
<?php
echo $_GET["eg"];
?>
</body>
</html>
with a URL of http:example.com/country/name/?eg=**NUMBER**
Use explode():
$parts = explode('/', $url);
$number = $parts[count($parts)-1];

php address into latitude and longitude

i am trying to convert the address into latitude.here's my code.
but its giving wrong latititude. if i put the address manually at $final place it gives the correct latitude.however i cant hard code it,whatever source comes in text box i have to find out that address latitude. what is the mistake?
<?php
$source=$_POST['textfield11'];
$dest=$_POST['textfield12'];
$time=$_POST['textfield13'];
$only = str_replace(',', '+', $source);
$final = str_replace(' ', '+', $only);
$url='http://maps.googleapis.com/maps/api/geocode/json?address=$final&sensor=false';
$source1 = file_get_contents($url);
$obj = json_decode($source1);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
?>
Instead of using str_replace, you should use urlencode.
<?php
$source=urlencode($_POST['textfield11']);
$dest=$_POST['textfield12'];
$time=$_POST['textfield13'];
$url='http://maps.googleapis.com/maps/api/geocode/json?address=$source&sensor=false';
$source1 = file_get_contents($url);
$obj = json_decode($source1);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
?>
<?
$final = urlencode($source);
$geo = simplexml_load_file("http://maps.google.com/maps/api/geocode/xml?address={$final}&sensor=false");
$lat = $geo->result->geometry->location->lat;
$lng = $geo->result->geometry->location->lng;
?>
Add a space after your , in the str_replace ... Cos at the moment, if the user types an address as "Somewhere road, That town" it will replace the ',' with a plus, and then the space resulting in: "Somewhere+road++That town" ... So something like this:
<?php
$source=$_POST['textfield11'];
$dest=$_POST['textfield12'];
$time=$_POST['textfield13'];
$only = str_replace(', ', '+', $source);
$final = str_replace(' ', '+', $only);
$url='http://maps.googleapis.com/maps/api/geocode/json?address=$final&sensor=false';
$source1 = file_get_contents($url);
$obj = json_decode($source1);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
?>

strip defined character from string

im having a odd problem os my website, i have a script that records all the searchs and insert those search words on database, the problem is that since search engine robots started sneaking around my website, they make my script to produce search keywords like "search keywords////////////////////////////////////////////////"
I want to strip that characteres ( ////////// ) before indexed on mysql.
This is what i have:
$search=htmlspecialchars($_GET['load']);
$say=mysql_query("SELECT * FROM madvideo WHERE MATCH (baslik) AGAINST ('*$search*' IN BOOLEAN MODE)");
$saydim=mysql_num_rows($say);
$count = $saydim;
$page = !empty($_GET["page"]) ? intval($_GET["page"]) : 1;
$s = ($page-1)*$perpage;
$sayfasayisi=ceil($count/$perpage);
if(ayaral("Arananlar-Kaydet")=="1") {
$ekle=cevir($search);
#mysql_query("insert into tag (baslik,tr,tarih) values ('$search','$ekle',now()) "); }
The variable " $search " will call the search word, and i dont know whats the strip syntax i have to use to strip that nasty ///////// character.
EDIT: the code that creates the words is this:
$vtitle = str_replace("\r\n\r\n", ' ', $vtitle);
$words = explode(' ', $vtitle);
$k = count($words);
$k3 = ceil($k/3);
$new = array();
for ($i=0; $i<$k; $i+=$k3) {
$new[] = join(' ', array_slice($words,$i, $k3));
}
$tag1 = $new[0];
$tag2 = $new[1];
$tag3 = $new[2];
Use MySQL TRIM function to remove from end of the string as follows:
TRIM(TRAILING '/' FROM <string>)
#mysql_query("insert into tag (baslik,tr,tarih)
values (TRIM(TRAILING '/' FROM '$search'),'$ekle',now())")
To trim from both beginning and ending, use following
TRIM(BOTH '/' FROM <string>)
#mysql_query("insert into tag (baslik,tr,tarih)
values (TRIM(BOTH '/' FROM '$search'),'$ekle',now())")
To remove all occurences of the string use REPLACE function as follows:
REPLACE(<string>, '/', '')
#mysql_query("insert into tag (baslik,tr,tarih)
values (REPLACE('$search', '/',''),'$ekle',now())")
Hope it helps...
If the / characters appear always at the end of the $search, you can use rtrim using the second (optional) parameter:
$search = "search keywords////////////////////////////////////////////////";
$search = rtrim($search, '/ ');
echo $search; // prints 'search keywords'
EDIT:
Real example...
<?php
if(isset($_REQUEST['str'])) {
$search = $_REQUEST['str'];
$ser_chk = strpos($search, "/");
if ($ser_chk > -1) {
$search = str_replace("/", "", $search);
}
}
?>
<h1><?php print $search; ?></h1>
<form action="" method="post">
<input type="text" size="100" value="search keywords////////////////////////////////////////////////" name="str" />
<input type="submit" />
</form>
LINK TO TEST: http://simplestudio.rs/tsto.php
At least do:
$search = mysql_real_escape_string($search);
Also you can check for that characters and if founded just replace them with empty string.
$ser_chk = strpos($search, "/");
if ($ser_chk > -1) {
$search = str_replace("/", "", $search);
}
$regex = "/\//";
$string = "////search";
$string = preg_replace($regex, '', $string);
echo $string;
The flexible solution for character repetition will be a regular expression.
$output = preg_replace('/\/[\/]+/', '/'. $input);
It will handle any number of "/" and replace it with a single "/".

Strip array of url and other characters, show only post name

The xml is like this: (wordpress url's) I want to strip them and get only the posts words.
http://www.site1.com/dir/this-is-page/
http://www.site2.com/this-is-page
How do i strip the url's and get only "this is page" (without the rest of the urls, and the "-") if i have two diffrent types of urls; one with dir and one without dir? Sample code bellow:
$feeds = array('http://www.site1.com/dir/feed.xml', 'http://www.site2.com/feed.xml');
foreach($feeds as $feed)
{
$xml = simplexml_load_file($feed);
foreach( $xml->url as $url )
{
$loc = $url->loc;
echo $loc;
$locstrip = explode("/",$loc);
$locstripped = $locstrip[4];
echo '<br />';
echo $locstripped;
echo '<br />';
mysql_query("TRUNCATE TABLE interlinks");
mysql_query("INSERT INTO interlinks (title, url) VALUES ('$locstripped', '$loc')");
}
}
?>
TY
Ty guys, did it like this:
$urlstrip = basename($loc);
$linestrip = str_replace(array('-','_'), ' ', $urlstrip);
You want only the last segment of the URL?
Try something like this.
$url = trim('http://www.site1.com/dir/this-is-page/', '/');
$url = explode('/', $url);
$url = array_pop($url);
$url = str_replace(array('-','_'), ' ', $url);
It's not very elegant... but it works.
replace
$locstripped = $locstrip[4];
with
$locstripped = $locstrip[count($loc) - 1];
if(!$locstripped)
$locstripped = $locstrip[count($loc) - 2];
$locstripped = str_replace('-', ' ', $locstripped);

Categories