I had a strange coding situation where I needed to have the URI become the title of the page being viewed. I couldn't think of another way to do it but now I need to format that URI and can't figure out how to accomplish it. It is a WordPress site so the URI is pretty clean. What I want to do is capitalize the letter of the first word and then a space, dash or pipe delimiter to separate out the title.
So this obviously gives me the URI:
<title><?php echo ($_SERVER['REQUEST_URI']) ?></title>
which gives me something like /test-catalog/diagnosis/flu. What I want to display is Test Catalog - Diagnosis - Flu
Thank you.
I would imagine this would work:
echo ucwords(str_replace(Array("-","/"),Array(" "," - "),$_SERVER['REQUEST_URI']);
By using str_replace and ucwords
Example
echo ucwords(str_replace('/', ' - ', str_replace('-', ' ', $_SERVER['REQUEST_URI'])));
several things to do:
$url = str_replace("-"," ",$url); // convert the - to spaces (do this first)
$url = str_replace("/"," - ",$url); // convert the / to hyphens with spaces either side
$title = ucfirst($url); // capitalize the first letter
if you want to capitalize each letter, then do this:
$title = ucwords($url); // capitalize first letter of each word
you might have some whitepsace begining and end, so do this:
$title= trim($title)
// remove the first slash '/'
$uri = substr($_SERVER['REQUEST_URI'], 1);
// ucwords to uppercase any word
// str_replace to replace "-" with " " and "/" with " - "
echo ucwords(str_replace(array("-","/"),array(" "," - "),$uri));
codepad
as a résumé of the previous answers:
echo ucwords(str_replace(array("-","/"),array(" "," - "),substr($_SERVER['REQUEST_URI'], 1)));
Related
I have the following title formation on my website:
It's no use going back to yesterday, because at that time I was... Lewis Carroll
Always is: The phrase… (author).
I want to delete everything after the ellipsis (…), leaving only the sentence as the title. I thought of creating a function in php that would take the parts of the titles, throw them in an array and then I would work each part, identifying the only pattern I have in the title, which is the ellipsis… and then delete everything. But when I do that, in the X space of my array, it returns the following:
was...
In position 8 of the array comes the word and the ellipsis and I don't know how to find a pattern to delete the author of the title, my pattern was the ellipsis. Any idea?
<?php
$a = get_the_title(155571);
$search = '... ';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
?>
I tried with the code above and found the ellipsis, but I needed to bring it into an array to delete the part I need. I tried something like this:
<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
global $wpdb;
$title_array = explode(' ', get_the_title(155571));
$search = '... ';
if (array_key_exists("/{$search}/i",$title_array)) {
echo "true";
}
?>
I started doing it this way, but it doesn't work, any ideas?
Thanks,
If you use regex you need to escape the string as preg_quote() would do, because a dot belongs to the pattern.
But in your simple case, I would not use a regex and just search for the three dots from the end of the string.
Note: When the elipsis come from the browser, there's no way to detect in PHP.
$title = 'The phrase... (author).';
echo getPlainTitle($title);
function getPlainTitle(string $title) {
$rpos = strrpos($title, '...');
return ($rpos === false) ? $title : substr($title, 0, $rpos);
}
will output
The phrase
First of all, since you're working with regular expressions, you need to remember that . has a special meaning there: it means "any character". So /... / just means "any three characters followed by a space", which isn't what you want. To match a literal . you need to escape it as \.
Secondly, rather than searching or splitting, you could achieve what you want by replacing part of the string. For instance, you could find everything after the ellipsis, and replace it with an empty string. To do that you want a pattern of "dot dot dot followed by anything", where "anything" is spelled .*, so \.\.\..*
$title = preg_replace('/\.\.\..*/', '', $title);
I'm trying to evaluate some strings containing dashes with the symfony ExpressionLanguage component.
Here is what I've got so far :
...
$string = 'user.chuck-norris.getId()';
$language = new ExpressionLanguage();
$evaluated = $language->evaluate($expression, $users);
...
This returns me the following error :
Variable "norris" is not valid around position 12. (Symfony\Component\ExpressionLanguage\SyntaxError)
If I change the dash "-" by an underscore "_", this works, but I have slug system which use dash and I dont wont to change it if I can avoid it.
Is there any solution?
Thanks
Like stated by Yonel, dashes are interpretated as operator.
So for this to work, I just have to replace dashes by undescores
$string = 'user.chuck-norris.getId()';
And then before making the request, replace _ by -
$value = str_replace('_', '-', $value);
If I have a string like this:
myPDF12345431234
what would be the proper PHP function call to str_replace so that everything after " " rel=.... " is replaced with nothing/blank?
For further clarity, The value in between the link tags is dynamic and unknown, so I can't call it.
I'm looking for something like:
$oldstring = array('<a href="', '" rel="" *until the end_of_string* ');
$replacewith = array=('', '');
$newstring = str_replace($oldstring, $replacewith, $URL);
What is the proper way to get everything after the URL (quotation mark til the end of the string) to be replaced with nothing?
This is handled by regular expressions. The following replaces everything from rel="" to the end of the string.
$newstring = preg_replace('/ rel="".*$/','',$oldstring);
The .* means "everything" and $ means "end of string". I added a space before rel because I assume you want to drop that as well.
Use preg_match:
preg_match("/(\<a href\=\\".*\\")\srel/", "myPDF12345431234", $output_array);
Var_dump($output_array);
http://www.phpliveregex.com/p/fqQ
It sounds like what you're actually looking for is the substring of your current string up until the end of your rel attribute.
$newstring = substr($oldstring, 0, strpos($oldstring, 'rel=""'));
Given the following URL:
http://www.domain.com/reporting/category-breakdown.php?re=updated
I need to remove everything after the .php
It might be "?re=updated" or it could be something else. The number of characters won't always be the same, the string will always end with .php though.
How do I do this?
To find the first position of a substring in a string you can use strpos() in PHP.
$mystring = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$findme = '.php';
$pos = strpos($mystring, $findme);
After, you have the position of the first character of your substring '.php' in your URL. You want to get the URL until the end of '.php', that means the position you get + 4 (substring length). To get this, you can use substr(string,start,length) function.
substr($mystring, 0, $pos + 4);
Here you are!
Find the first indexOf (".php"), then use substring from char 0 to your index + the length of (".php");
3 line solution:
$str = "http://www.domain.com/reporting/category-breakdown.php?re=updated";
$str = array_shift(explode('?', $str));
echo $str;
Note: it's not fool-proof and could fail in several cases, but for the kind of URLs you mentioned, this works.
Here is another way to get the non-query-string part of a url with PHP:
$url = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$parsed = parse_url($url);
$no_query_string = $parsed['scheme'] . '://' . $parsed['hostname'] . $parsed['path'];
// scheme: http, hostname: www.domain.com, path: /reporting/category-breakdown.php
That will handle .php, .phtml, .htm, .html, .aspx, etc etc.
Link to Manual page.
I've built a custom CMS that does the usual things: post management, content management, contact management, etc.
In the post management section, I would like to extract the "Title" field and convert this into a URL-ready form.
Example: New post is created titled "3 Ways to Win in Real Estate & in Life". I want this to run through a PHP script that turns it into "3_ways_to_win_in_real_estate_&_in_life".
Anyone have a script for this, or would url_encode() do all of this for me?
Make use of currently developed code that you can use within your own projects.
Kohana 3 framework has solution for you. Below you can find solution on the basis of URL::title() method from Kohana 3 framework:
function title($title, $separator = '-') {
// Remove all characters that are not the separator, letters, numbers, or whitespace
$title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', strtolower($title));
// Replace all separator characters and whitespace by a single separator
$title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
// Trim separators from the beginning and end
return trim($title, $separator);
}
function cleanURL($string)
{
$url = str_replace("'", '', $string);
$url = str_replace('%20', ' ', $url);
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url); // you may opt for your own custom character map for encoding.
$url = strtolower($url);
$url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
return $url;
}
// echo cleanURL("Shelly's%20Greatest%20Poem%20(2008)"); // shellys-greatest-poem-2008
from here. You can write your own or possibly find one to replace things like & with and, and so on.
Also note that this function uses dashes, not underscores. The preferred way to create clean URLs is with dashes, not underscores.
This is basic, but works.
static public function slugify($text)
{
// replace all non letters or digits by -
$text = preg_replace('/\W+/', '-', $text);
// trim and lowercase
$text = strtolower(trim($text, '-'));
return $text;
}
From here:
http://www.symfony-project.org/jobeet/1_4/Doctrine/en/05
"Anyone have a script for this, or would url_encode() do all of this for me?"
Have you tried using url_encode() to do this for you? A quick test script would have revealed that much for you, or even using functions-online.com's urlencode() tester.
$str = '3 Ways to Win in Real Estate & in Life';
echo urlencode( $str );
// 3+Ways+to+Win+in+Real+Estate+%26+in+Life
You could use a simple preg_replace() and simple replace anything which is not a letter or digit with either an underline or a dash.
echo preg_replace( '/[^\d\w]+/' , '_' , $str );
// 3_Ways_to_Win_in_Real_Estate_in_Life
echo preg_replace( '/[^\d\w]+/' , '-' , $str );
// 3-Ways-to-Win-in-Real-Estate-in-Life
Just use a dash of str_replace to turn the spaces into underscores, and a sprinkle of urlencode to catch the rest.
Edit: I missed the strtolower part, but I think you had a handle on that.
This is of course just a basic way to go about it, if you want to exactly imitate the wordpress way of turning a text into a URL, have a look at that code, it's open and available for you to do so.