tags:

views:

163

answers:

3

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 '.'; } ?>
+3  A: 

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.

Jeremy Morgan
That should be `($question != '?')`. You're comparing against the negation of `$question` now.
mercator
Yes, that's correct as well.
Jeremy Morgan
+2  A: 

Just providing the fixed version of Jeremy's answer:

<?php $mytitle = get_the_title(); echo $mytitle; ?>
<?php $question = substr($mytitle, -1); if ($question != '?') { echo '.'; } ?>
UltimateBrent
Actually, this works but Jeremy's doesn't. I don't know enough php to know why, but it must have something to do with your { and } constructs around the echo. Thanks; my punctuation was bugging me for some time and had to edit my post title listings most weeks.... Thanks to mercator, too.
songdogtech
A: 

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?

dreeves