Reputation: 17561
Problem: some of the post titles on my WordPress site are questions, i.e. the post title ends with a question mark. And I have post queries that generate lists of the most recent posts. So I'm trying to figure out a bit of php that will keep my punctuation correct.
What's a good way to determine if the last character of a title is a question mark and not echo a period? And if the post title is a not a question, echo a period.
This is what I am trying to use to get the title in a wordpress query and then determine if the title is a question, but it doesn't print the period.
Must be something simple I have wrong here:
<?php $mytitle = get_the_title(); echo $mytitle; ?>
<?php $question = substr($mytitle, -1); if (!$question = '?'): echo '.'; endif; ?>
Edit 3/03/10
This now works:
<?php $mytitle = get_the_title(); echo $mytitle; ?>
<?php $question = substr($mytitle, -1); if ($question != '?') { echo '.'; } ?>
Upvotes: 3
Views: 1409
Reputation: 26932
Your code could end up appending a period when there already was one. I suggest starting with this:
<?php
# add a period if it doesn't already end with punctuation.
function punc($s)
{
if(preg_match("/[\.\?\,]$/", $s)) return $s;
return $s . ".";
}
echo punc(get_the_title());
?>
You can then make the punc() function fancier as needed. For example, what if a title ends with a comma?
Upvotes: 1
Reputation: 23702
Just providing the fixed version of Jeremy's answer:
<?php $mytitle = get_the_title(); echo $mytitle; ?>
<?php $question = substr($mytitle, -1); if ($question != '?') { echo '.'; } ?>
Upvotes: 2
Reputation: 3372
Untested, but the first thing I noticed is you're using = which indicates assignment, not comparison.
if (!$question = '?'): echo '.'; endif;
Should be:
if (!$question == '?'): echo '.'; endif;
So it looks like:
<?php $mytitle = get_the_title(); echo $mytitle; ?>
<?php $question = substr($mytitle, -1); if (!$question == '?'): echo '.'; endif; ?>
Hope that helps.
Upvotes: 3