Francesco
Francesco

Reputation: 25239

Php: detect single letter in a string surrounded by special characters

Say i have these strings

tavern-o-fallon-new-york
cut-n-shoot-texas
cut-n-shoot-texas-at-o-fellon

I'd like to to detect all the occurrences of the -o-, or any other pattern, and convert to o'

so i can convert the string to

Tavern O'Fallon New York
Cut'N'Shoot Texas
Cut'N'Shoot Texas At O'Fellon

I believe i can use some array of common patterns like the O', 'N' etc..

Upvotes: 0

Views: 73

Answers (1)

ka_lin
ka_lin

Reputation: 9432

I`d use str_replace:

$phrase = 'tavern-o-fallon-new-york
cut-n-shoot-texas
cut-n-shoot-texas-at-o-fellon';
$phrase = str_replace(array('-n-','o-','-'),array('`N`','O`',' '), $phrase);
echo ucwords($phrase);

Output:

Tavern O`fallon New York
Cut`N`shoot Texas
Cut`N`shoot Texas At O`fellon

Edit:

To fix the lowercase letters:

$phrase = str_replace(array('-n-','o-','-'),array('`N` ','O` ',' '), $phrase); // add an extra space after the quote;
$phrase = ucwords($phrase); //then ucfirst can do the job
$phrase = str_replace('` ','`', $phrase); //remove the extra space
echo $phrase;

Upvotes: 1

Related Questions