Technotron
Technotron

Reputation: 19

Preg Replace php

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

Answers (4)

rid
rid

Reputation: 63442

$news = ucfirst(trim(preg_replace('/(?:_|\.php$)/i', ' ', end($parts)));

To explain:

  • ucfirst() uppercases the first character in a string
  • trim() trims spaces from the beginning and end of the string
  • preg_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 string

Upvotes: 0

George Cummins
George Cummins

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

mario
mario

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

KingCrunch
KingCrunch

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

Related Questions