How to replace certain characters

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

How to replace certain characters

Post by dreamline »

Hi All,
I can't seem to grasp regex and find a solution to my problem. Here's the thing. Suppose I have references like: top_left_image and bottom_right_image. I want to get the first letters of each word. So for the top_left_image I want to get the letters "tli" and for the bottom_right_image I want to get the letters "tri". I've tried a dozen combinations with regex but I am not very good in regex, so I hope someone can help me out with this.

Thanks for any help. :)
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How to replace certain characters

Post by Eric! »

I suck at regex. I was bored so I thought I'd give you and old school method. It assumes the words you want to extract are seperated by spaces, then it looks for underscores within those words and pulls out the first character of each word. Then it builds a little array of results and returns it.

Code: Select all

<?php
$test="junk here top_left_image junk there bottom_left_image and more junk";
echo var_dump(Get_Letters($test));

function Get_Letters($string,$token='_')
{
    $result=array();
    $count=0;
    $lines=split(' ',$string); // chop up by spaces
    foreach($lines as $line)
    {
        if(substr_count($line,$token)>0)
        {
            $temp=split($token,$line);
            foreach($temp as $tmp)
            {
                $result[$count].=$tmp[0]; // pull off first letter
            }
            $count++;
        }
    }
    return $result;
}
?>
so the output is
[text]array(2) { [0]=> string(3) "tli" [1]=> string(3) "bli" }[/text]
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Re: How to replace certain characters

Post by dreamline »

HI Eric,
Thanks, but the old school method is what I'm trying to avoid. I would have used explode instead of split but other than that mainly the same. :)
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: How to replace certain characters

Post by ridgerunner »

The following regex matches underscore separated words, where there are at least two but no more than four words and each word begins with a letter but may contain letters and digits. It is fully commented so it should be pretty easy to modify to meet your precise needs. The following command line script demonstrates how to extract the first letters and combine them into a shortened string.

Code: Select all

<?php // test.php 2010-10-19
$data = "this string has two_words three_words_here and four_words_in_here and more string";
$re = '/# match underscore separated multi_word (2-4 words)
    \b           # anchor start to word boundary
    ([A-Z])      # $1 first letter of 1st word
    [A-Z0-9]*    # remainder of 1st word
    _            # underscore separates 1st and 2nd
    ([A-Z])      # $2 first letter of 2nd word
    [A-Z0-9]*    # remainder of 2nd word
    (?:          # third word is optional
      _          # underscore separates 2nd and 3rd
      ([A-Z])    # $3 first letter of 3rd word
      [A-Z0-9]*  # remainder of 3rd word
    )?           # third word is optional
    (?:          # fourth word is optional
      _          # underscore separates 3rd and 4th
      ([A-Z])    # $4 first letter of 4th word
      [A-Z0-9]*  # remainder of 4th word
    )?           # fouth word is optional
    \b           # anchor end to word boundary
    /ix';
$count = preg_match_all($re, $data, $matches, PREG_SET_ORDER);
for ($i = 0; $i < $count; $i++) {
    $letters = "";
    for ($j = 1; isset($matches[$i][$j]); $j++)
        $letters .= $matches[$i][$j];
    printf("Match %d = \"%s\", first letters = \"%s\"\n",
        $i + 1, $matches[$i][0], $letters);
}
?>
 
Here is the output from the script:
[text]Match 1 = "two_words", first letters = "tw"
Match 2 = "three_words_here", first letters = "twh"
Match 3 = "four_words_in_here", first letters = "fwih"[/text]

Hope this helps!
:)
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: How to replace certain characters

Post by s.dot »

You do not need regex if you already have the strings you need.. just some simple string manipulation such as using strpos() and / or iterating through the string as an array and checking characters and position.. or using explode() and getting the first letter of each piece, for example:

Code: Select all

$str = 'top_left_image';

function firstLetter($str)
{
    return $str[0];
}

$pieces = explode('_', $str);
echo implode(array_map('firstLetter', $pieces));
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Re: How to replace certain characters

Post by dreamline »

Thanks guyz. I think that last option (user defined function) would be my choice. :) I will also have a look at the other options :)

This will definately help me out on getting more insights. :)
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How to replace certain characters

Post by Eric! »

FYI on s.dot's solution, if the string contains other items it will fail. For example $str="hello test_image_location goodbye" would return hil.

Ridgerunner, nice regex. Is it faster?

edit: I tried them out...
regex average: 0.0030 seconds
old_school: 0.00041 seconds.
Post Reply