开发者

How to suffix apostrophe-s, with optional middle name and last name?

I'm trying to display the apostrophe 's after the full name for example Samuel L. Jackson’s but if the last name or middle name is left out the 's is prefixed by a space, for example: Samuel ’s. Can some one help me c开发者_Go百科orrect this problem?

Thanks

Here is the PHP code.

if(!empty($first_name) || !empty($middle_name) || !empty($last_name)) {
    echo = $first_name . ' ' . $middle_name . ' ' . $last_name . ' \'s';
}


$text = array();
if(!empty($first_name)) {
    $text[] = $first_name;
}
if(!empty($middle_name)) {
    $text[] = $middle_name;
}
if(!empty($last_name)) {
    $text[] = $last_name;
}

if(count($text) > 0) {
    echo implode(' ', $text).'\'s';
}


echo trim($first_name . ' ' . $middle_name . ' ' . $last_name). ' \'s';

should do the trick?

One more issue: If you have a first and last name, there will be two spaces in between... is that going to be a problem at some point?


echo trim($first_name . ' ' . $middle_name . ' ' . $last_name) . '\s';

trim will get rid of any trailing spaces.


$a = ""
if (!empty($first_name)
  $a .= $first_name . " "
if (!empty($middle_name)
  $a .= $middle_name . " "
if (!empty($last_name) 
  $a .= $last_name . " 's"

This should do the trick.


Why are you using Single Quote ? You could simply use "'s" no need of escaping.

echo $first_name.(empty($middle_name) ? '' : $middle_name.' ').$last_name."'s"

alternative

$names = array($first_name);
if(!empty($middle_name))
  $names[] = $middle_name;
$names[] = $last_name;
echo implode(' ', $names)."'s";


echo
  (empty($first_name) ? '' : $first_name) .
  (empty($middle_name) ? '' : ' ' . $middle_name) .
  (empty($last_name) ? '' : ' ' . $last_name) . "'s";

If the variables will always be set:

echo str_replace(
  '  ',
  ' ',
  $first_name . ' ' .
  $middle_name . ' ' .
  $last_name . "'s");

To display a proper single quote in HTML, replace the ' with ’, which displays as ’.


may be

echo htmlspecialchars($full_name, ENT_QUOTES);

will solve the problem


$full_name = trim($first_name.' '.$middle_name);

if(!empty($full_name) && !empty($last_name)){
  $full_name .=' '.$last_name."'s";
  echo $full_name;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜