Reputation: 19
I've got the phrase "rising_car_insurance_costs.php" I want to use preg_replace to remove the .php:
$news = preg_replace('/^[a-zA-Z0-9_\.\-]+[.php]/', '$1 + ''', end($parts));
I also want to replace the _ with a space which I can do but I also want to make the first letter a capital letter (if it's a letter) -is that even possible?
Thanks Sam
Upvotes: 0
Views: 346
Reputation: 63442
$news = ucfirst(trim(preg_replace('/(?:_|\.php$)/i', ' ', end($parts)));
To explain:
ucfirst()
uppercases the first character in a stringtrim()
trims spaces from the beginning and end of the stringpreg_replace()
replaces the following regular expression (case insensitive, /i
) with whitespace
(?:...)
is a non-capturing expression, useful for using the |
later_
means any "_" character|
means "or"\.php$
means the sequence ".php" at the end of the stringUpvotes: 0
Reputation: 28906
Easier without preg_replace:
$without_php = str_replace( '.php', '', end( $parts ) )
$without_underscores = str_replace( '_', ' ', $without_php );
$uppercased = ucfirst( $without_underscored);
All in one:
$result = ucfirst( str_replace( array( '.php', '_' ), array( '', ' '), end( $parts ) ) );
Upvotes: 0
Reputation: 145482
It looks like you want to use preg_replace_callback
and do the other stuff there:
$news = preg_replace_callback('/^([a-zA-Z0-9_\.\-]+)[.php]$/', 'rewrite',
function rewrite($match) {
$str = $match[1];
... strtr("_", " ");
... ucwords();
return $str;
}
Upvotes: -1
Reputation: 131871
No need for regular expression
I want to use preg_replace to remove the .php:
$news = basename(end($parts), '.php');
I guess $parts
mean, that you splitted a path using explode()
with /
. When you use basename()
you can avoid this step too.
I also want to replace the _ with a space
$news = str_replace('_', ' ', $news);
I also want to make the first letter a capital letter
$news = ucfirst($news);
Upvotes: 2