SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Posts
    31
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    preg_match formula

    Im altering another developers code (without luck) - its an addition to some preg_replace formulas so I don't want to break anything. Hopefully I can explain this correctly:

    The code is currently setup as follows:

    PHP Code:
    const EXERCISE_FILE_TITLE_RULE "^(?:[0-9.]+)[-_]+(.*)\.mp3$";
    const 
    SPACE_REPLACER '_';

    $filename 23-Z_ae.mp3;

    if ( 
    preg_match('/'EXERCISE_FILE_TITLE_RULE ."/i"$file_name$m ) ) {
        
    $info['title'] = preg_replace
                            array( 
    '/'SPACE_REPLACER ."+/i"'/'KEYWORDS_REPLACER ."/i" ),
                            array(
    ' 'null),
                            
    $m[1] );

    This produces the correct result:

    PHP Code:
    Array
    (
        [
    title] => Z ae

    I need to change the preg_replace expression so that if recognises if the additional following pattern is in the $filename:

    PHP Code:

    $filename 
    23-_[Z]__ae.mp3
    It needs to pickup the letter or letters inside _[ ]_

    In this case something like this would be produced:

    PHP Code:
    Array
    (
        [
    title] => *Zae

    Can anyone please help?

  2. #2
    SitePoint Enthusiast
    Join Date
    Oct 2011
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Without knowing more about the possible filenames that need to qualify for this regex, I came up with this quick solution that outputs what you need.

    PHP Code:
    $badcharacters = array('#_+#''#[\[\]]+#');
    $replacements = array(' ''*');

    $filename1 '23-Z_ae.mp3';
    $filename2 '23-[Z]__ae.mp3';

    $regex "#^[0-9]+[_-](.+)\.mp3$#Ui";

    preg_match($regex$filename1$match1);
    preg_match($regex$filename2$match2);

    $match1[1] = preg_replace($badcharacters$replacements$match1[1]);
    $match2[1] = preg_replace($badcharacters$replacements$match2[1]);

    print_r($match1);
    print_r($match2); 
    The above code outputs:

    Code:
    Array
    (
        [0] => 23-Z_ae.mp3
        [1] => Z ae
    )
    Array
    (
        [0] => 23-[Z]__ae.mp3
        [1] => *Z* ae
    )


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •