Designer
Designer

Reputation: 895

How to remove the last word and the last letter if is an 'n' of the first word of a text using php

I 'm trying to remove the last word and the last letter (specific if is an 'n') of the first word of a text using php.

Here is a simple example with first name and last name:

John Doe must become Joh

Right now i use the code below to remove completely the last name.

<?php 
$firstname = stripos('John Doe', ' ');
echo substr('John Doe', 0, $firstname); 
?>

The result is John

How can i modify my code so the last letter from the name will be also removed ONLY if is an 'n'?

Upvotes: 0

Views: 35

Answers (2)

Gavin
Gavin

Reputation: 2365

This should work, assuming you always have a name of at least two parts. It'll get upset otherwise. Very odd use case.

$name = "John Doe";

$parts = explode(' ', $name);
if(strpos($parts[0], 'n') == strlen($parts[0])-1){
    echo substr($parts[0], 0, strlen($parts[0])-1); // Joh
}

Upvotes: 1

Abolfazl Ghaemi
Abolfazl Ghaemi

Reputation: 454

try this :

<?php 
    $firstname = stripos('John Doe', ' ');
    $firstname = substr('John Doe', 0, $firstname); 
    if (substr($firstname, -1) == 'n') {
        echo substr($firstname, 0, -1);
    };
?>

Upvotes: 1

Related Questions