Eric Binnion

  • How American parenting is killing the American marriage

    Refreshing thoughts on parenting. I always find it interesting to see people’s reactions when I criticize my son.

  • Mend Walk 2014

    Sara, Hero, and I went to the MEND walk in Irving, Tx today. 

    Here is a picture I took of Hero writing a letter to Scarlett, which he planned to attach to a balloon so it reached her in heaven.

    IMG_1365-8.JPG

  • Get Most Visible Element on a Web Page

    Recently, I was working on updating keyboard shortcuts for o2 and came across a unique shortcut.

    When pressing r, we wanted to open the reply box for the most visible post. When I first started thinking about this requirement, I found myself thinking: “How the hell can I determine what the most visible post is?”

    Attaching to Scroll Event

    One of the first things that crossed my mind was that I could attach to the window scroll event and then update a mostVisiblePost variable as needed. For example, when a scroll event occurs:

    • Get all posts on the page
    • Check which posts are in the viewport
    • Get the offsets for each and try to determine which is most visible.

    I wasn’t quite fond of this method because it could make scrolling janky and seemed prone to error.

    An Alternative Surfaces

    While I was reading Javascript: The Definitive Guide I came across the JavaScript method elementFromPoint(x,y).

    As I thought more about getting the most visible element on the page, I came up with the idea of creating a grid of points that covered the page. I could then get the element at each point and traverse up the DOM to find which post was at that point.

    After thinking through this a bit more, I decided to go for it and came up with the following solution:

    [javascript]
    // Note that Underscores and Backbone are being used here.

    //Let’s create a grid of points in the top half of the viewport.
    var viewPortWidth = $( window ).width(),
    viewPortHeight = $( window ).height(),
    xCoords = _.map( [ .2 , .4, .6, .8 ], function( num, key ){ return num * viewPortWidth; } ),
    yCoords = _.map( [ 0, .1, .2, .3, .4 ], function( num, key ){ return num * viewPortHeight; } );

    /*
    * For each coordiante pair (x,y), get element at point,
    * traverse up to find a post, and add post ID to elems.
    */
    var elems = [];
    _.each( yCoords, function( y ){
    _.each( xCoords, function( x ){
    var element = $( document.elementFromPoint( x, y ) ),
    closest = element.closest( o2Keyboard.threadContainer + ‘.post’ );

    if ( closest.length > 0 ) {
    elems.push( closest.attr( ‘id’ ) );
    }
    });
    });

    // Find most frequent (mode) post ID in elems array.
    // Thanks Matthew Flaschen – http://stackoverflow.com/a/1053865
    if ( elems.length > 0 ) {
    var modeMap = {};

    var maxEl = elems[0],
    maxCount = 1;

    _.each( elems, function( el ){
    if ( modeMap[ el ] == null ) {
    modeMap[ el ] = 1;
    } else {
    modeMap[ el ]++;
    }

    if ( modeMap[ el ] > maxCount ) {
    maxEl = el;
    maxCount = modeMap[ el ];
    }
    });
    }
    [/javascript]

    For the purposes of O2, we defined the most visible post to be in the top 40% of the viewport. So, we created an array of y points from 0-.4 times the viewport height. We then created an array of x points that covered most of the viewport.

    Once we’ve created the xCoords and yCoords arrays, we then loop over these two arrays and get the element at each (x,y) coordinate pair. In this example, we will be creating 20 unique (x,y) coordinate pairs. You can fine tune that for your needs.

    Once we have the element at each point, we traverse up the DOM to see if there is a post. If there is, that post’s ID gets added to an array.

    We then take a mode, essentially finding the post with the most hits, on the elems array and that is the most visible post.

    Questions or Comments?

    If you have any questions or comments about this method, feel free to leave a comment below.

  • Why Concatenate Files in WordPress?

    One of the easiest things that you can do to increase the speed of your website is to concatenate the CSS and JavaScript files that are loaded on your site.

    This only takes a couple of minutes since all you need to do is install a plugin. For this, I have typically used WP Minify, but have also occasionally used Better WP Minify.

    What is Concatenation?

    Sure, I can tell you that concatenation will help speed up your site, and you can easily install a minification plugin… but why does concatenation help?

    First, to understand why concatenation helps, we need to understand what concatenation is.

    Simply, concatenation is the combining of files into one large file.

    For example: Instead of loading many CSS and JavaScript files for the many plugins that your site has enabled, these files would be combined into one large CSS and one large JavaScript file.

    How Does Concatenation Help?

    To understand why concatenating files is beneficial, let’s consider the act of having to bring in many grocery bags.

    Imagine that there are 12 bags in the trunk of your car. You have the option of taking all 12 bags in one trip or taking a trip for each bag.

    If you take all 12 bags in one trip, the trip will likely take a bit longer since you’re carrying more weight. But, if you take multiple trips, then you’re traveling the same distance many many times.

    Arguably, taking all 12 bags in one trip will require more effort but will be faster.

    This is very similar to why concatenation helps speed up your site. Instead of the browser having to take multiple trips to the server to download several JavaScript and CSS files, these files are packaged into just two larger files.

    While these larger files themselves will take a bit longer to download, the browser isn’t having to take multiple trips back to the server to download individual files.

  • Canyons Resort Property

    IMG_1334.JPG

    This picture of Canyons Resort as taken on Sunday while it was lightly sprinkling
  • Automattic Hot Dog Eating Competition

    IMG_1310-0.JPG

    At the Saturday evening grand meeting flash talks, there was a very unexpected hot dog eating competition. Rose killed the competition!

  • Automatticians Karting

    Part of meetups for Automattic are having fun with other Automatticians.
    Earlier in the week I got a tattoo and played paintball, but today was all about indoor go-karting

     

  • 9 Weeks at Automattic

    As of September 15th, I have been at Automatic for 9 weeks! The first three weeks were spent on support rotation and the last six weeks have been spent actually working on Team Mercury.

    The annual Grand Meetup is also currently happening, during my 10th week, and it’s been great to play paintball, learn some Android development, experiment with the Dvorak keyboard, and much more with my coworkers. I’ve added a coworker selfie with fellow Automatticians that played paintball as the featured image for this post.

    I’d like to share my thoughts about Automattic after actually being with the company and on my team for a small period of time.

    I Will Never Stop Learning

    This is currently the first statement of the Automattic creed. I believe that work at Automattic embodies this concept very much.

    For starters, we work on very exciting projects and are always pushing to make better software. Not only that, but there are so many different projects at our company that use exciting tools/frameworks/languages, that any person can truly learn whatever they want. In short, there is no shortage of things to learn.

    Further, the fact that Automattic allows employees to do rotations and temporarily work on other teams is great because it allows Automatticians to expand their knowledge as well as determine if they are on the correct them for themselves.

    I Will Never Pass Up an Opportunity to Help Out a Colleague

    Automatticians are generally very happy and helpful people. To all of the Happiness Engineers that answered my questions when getting familiar with the various support interfaces – Thank you for much for your help.

    To Team Mercury who has been so helpful, thanks for putting up with my general lack of knowledge in all things JavaScript.

    Enjoying the Hard Stuff

    My Mom often praises me for how “smart” I am, even though that I believe I am of average intelligence. That being said, I do think the one thing that sets me apart from many others is my general fearlessness in regards learning new things.

    I feel that the best opportunities for growth and learning are in doing the hard tasks.

    At Automattic, I feel that our company does a great job of embracing hard tasks. For example, taking P2 and making it better with O2 and Backbone. Or, the new Tinker team whose goal is to build new and exciting things (per my understanding).

    I also feel that Automatticians generally try to get things “right” as opposed to just getting things “working”. This is a key paradigm shift from working at a design agency where it was more important to just getting things working.

    Dream Job

    Overall, Automattic is a dream job and I enjoy working here!

  • My Boss is a Badass

    Beau Lebens the Badass

    As I flew to WordCamp NYC this weekend, I decided that I would re-read Year Without Pants and see what I took from the book now that I actually work at Automattic.

    First thing I took away… It’s very surreal to read about your company and/or your experiences in a published book.

    Second thing I took away… My team lead is a badass. Seriously, how many developers can you name that have been in a published book, know Krav Maga (or some other martial arts or self-defense), and been through survival training??

    Off of the top of my head, none.

    On a side note: If you’re interested in working at Automattic or interested in how distributed companies such as Automattic work, give Year Without Pants a read!

  • WordCamp NYC 2014

    This past weekend I had the opportunity to travel to WordCamp NYC.

    This was a great opportunity for several reasons because I was able to meet some of my coworkers for the first time and I was able to experience NYC.

    I even made some people happy by fixing their WordPress issues at the Happiness Bar.

    Meeting Automatticians

    Because Automattic is a distributed company, and I just started three weeks ago, WordCamp NYC was the first time I had met many of my coworkers in person.

    This was a real treat as Automattic is comprised of many interesting individuals.

    Spencer Berry

    Take Spencer Berry for example who can YoYo like a beast without while also holding a conversation.

    I also had the pleasure of meeting many other Automatticians such as:

    • Kevin Conboy
    • Alx Block
    • Erica Varlese
    • Richard Spees
    • Mel Choyce
    • Konstantin Obenland
    • JR Tashjian

    Experiencing NYC

    I feel like the conference worked out pretty well where there was plenty of work, social time, and exploring. Not only did I have the chance to experience some great BBQ, chicken, and local pizza…

    But, I was also able to see Times Square, the Statue of Liberty, and the 9/11 memorial.

    Here are some various pictures from around NYC.

  • My Son Had His First Fight Today…

    image

    Normally picking my son up from his karate classes/daycare is a fairly routine procedure. I walk in, tell him to put his shoes on, and then remind him to hurry up and put his shoes on for what seems like 5 minutes…

    But today, as soon as I walked in, I was told that I had to talk to the lady in charge before I left for the day.

    The first thought in my head was something along the lines of, “What the hell did my son do?”

    The Meeting

    After talking to the lady in charge, I was told that my son had jumped onto another kid and began wrestling him after the kid took my son’s money. The kid then punched my son in the face.

    My initial reaction was to agree with the karate instructors and chastise my son for wrestling with the kid.

    After all, my son could have just gone to a karate instructor and asked for him or her to mediate.

    Somewhat surprisingly, I wasn’t afraid or mad that my son had been punched in the face. In fact, I fully expect that he’ll take several more blows to the face over the next few years in his karate classes.

    Thinking Through The Actions

    As I drove home, with Hero in the back seat, I began to work through what exactly happened and I realized that I was proud of my son for getting in a little scuffle.

    I realized that had I been in the same situation, my reactions would have likely been similar.

    The more I thought about the situation, the more proud I was of my son that he had stuck up for himself and wrestled the boy.

    This doesn’t mean that fighting should be one’s first reaction. And Hero should have likely found another way of getting his money back.

    But in the end, I’m proud to see that my son has a backbone and he’s not afraid to use it when necessary.

  • #21 – In order to understand recursion, one must first understand recursion.

    Understand Recursion

    I found this amusing since recursion is definitely one of the computer science subjects that I struggled with the most in university.

    I remember having to manually draw stacks on paper to keep track of values and how deep in recursion I was.

    I might have to see how much it costs to print this on a poster!

  • Basic Authentication in WordPress

    About a month ago, I worked on a plugin to help retrieve a lawyer’s reviews from the AVVO API. One of the key aspects of connecting with the AVVO API was using basic authentication, which was a new method of connecting to an API for me.

    What is Basic Authentication?

    Basic authentication requires that an authorization header be sent that contains the following:

    [code lang=”php”]
    ‘Basic ‘ . base64_encode( "{$username}:{$password}" )
    [/code]

    That is the string Basic, followed by a base 64 encoded string comprised of a username, colon, and then password.

    Implementing Basic Authentication in WordPress

    One of my favorite tools in WordPress is the HTTP API. Not only does it handle different server configurations and simplify the process of making API calls, but it makes setting headers as simple as passing an array of arguments.

    Here is an example of how I implemented the basic authentication API call.

    [code lang=”php”]
    function make_basic_auth_request( $api_url, $username, $password ) {
    $request = wp_remote_get(
    $api_url,
    array(
    'headers' => array(
    'Authorization' => 'Basic ' . base64_encode( "{$username}:{$password}" )
    )
    )
    );

    if ( is_wp_error( $request ) ) {
    return $request;
    } else {
    return json_decode( wp_remove_retrieve_body( $request ) );
    }
    }
    [/code]

    The function above will return a WP_Error object if the API call fails or a JSON decoded string if the API call was successful.

    A Real Life Example

    I have published the WordPress plugin I built to get AVVO reviews on Github.

    Note: This plugin only implements the reviews portion of the AVVO API, and its purpose was solely to factor out code from a custom theme. As such, it should not be looked at as complete.

  • Becoming an Automattic Code Wrangler : Beginning to End

    Looking back, I remember how anxious I was throughout the whole process of applying, interviewing, and going through trial at Automattic… I also remember that while there are many stories of the process for Happiness Engineers, there were very few for Code Wranglers.

    Because of this, I’d like to share my experience from applying to accepting the job offer.

    Applying to Automattic

    Applying to Automattic is a pretty straight forward process. Go to Automattic’s Work With Us page, find your job, then send an email that follows the instructions at the bottom of the page.

    After that, sit back and relax. It took a little over 6 weeks to get a response back to my application.

    Interviewing and Code Test

    If you make it past the application stage, then the next step is interviewing, which will likely be with a Code Wrangler.

    While the content of the interview was similar to other tech interviews that I’ve had, the format was different … The interview was a text chat interview.

    Why, you ask?

    Well, since Automattic is a completely distributed company, meaning that people work all over the world, much of the communication takes place in the form of text chat. Thus, it makes sense to conduct interviews in the same format that most communication takes place.

    As a matter of fact, you can probably expect to communicate solely through text chat throughout the entire hiring process!

    If you make it past the interview, then you’ll be given a small coding problem to work on and a due date … This is the code test.

    Trial for Code Wranglers

    If you successfully make it past the code test, then the next step is the trial.

    For my trial, I built a message and error logging API called WP Logger.

    The thing that stands out the most about my trial is that there weren’t any hard requirements. My trial lead, Demitrious Kelly, told me to build a logging API, provided a bit of guidance, and set me loose. From there, I iterated quickly and gave him updates throughout the week to get feedback and guidance.

    Realizing that this was an audition of sorts, I made it a point to try to answer as many questions as possible by myself. This meant looking at documentation, reading core WordPress code, and more… All before asking a question.

    At points, Demitrious provided suggestions that completely changed the direction the project went in. Example: Where I provided a global instantiation of the WP_Logger class that developers could use to log messages… Demitrious suggested to use the WordPress hooks API, which made the code much simpler.

    In the end, my trial lasted about 4-5 weeks. After which I was told to get in touch with Matt Mullenweg, the founder of Automattic, via Skype.

    The Matt Talk for Code Wranglers

    The Matt Talk is the last step in the hiring process for Automattic. But, be forewarned, Matt is not an easy person to get in touch with. It took about 10 days before Matt responded to my initial Skype message.

    The talk lasted about 3.5 hours, the end of which was spent on setting a range on salary. Matt welcomed me aboard and I received my offer letter the next day.

    Questions?

    A lot has happened over the span of about 10 weeks, so there’s a good chance that I might have missed a few interesting details. So, if there’s something you’re curious about, leave a comment below, and I’ll attempt to answer your question.

  • I’m Joining the Automattic Family

    I’m extremely proud to announce that I’m joining Automattic as a Code Wrangler starting on July 14th, 2014.

    true == is_automattician()

    For those that don’t know, Automattic was founded by Matt Mullenweg (a founding WordPress developer) and is the force behind WordPress.com, a hosted version of WordPress, and many other services such as:

    The pay and benefits are amazing, but most important is that with WordPress.com serving over 409 Million people and more than 14.5 Billion pages per month… I’ll be working for a company that affects millions of people daily.

    Hello Team Mercury!

    After spending the initial 3 weeks on support rotation, I’ll be working with Team Mercury whose primary project is O2. O2 is a communication/project management tool built on top of WordPress.

    Here is a video where Beau Lebens, my team lead, discusses O2:

    I’m very excited for the rest of this year! I can’t wait to get started in a few weeks.

  • Parse RSS in ExactTarget

    I was recently tasked with migrating a few themes from Mailchimp to Exact Target. While the overall experience I had working with ExactTarget was much less than stellar, I most disliked working with RSS feeds. The whole process of parsing an RSS feed seemed awkward.

    So, in an effort to help others, and because I never want to figure out how to parse RSS for Exact Target again, here is how you can use RSS feeds within your Exact Target templates.

    Create a Content Area

    The method described to me by Exact Target’s support requires that the RSS be stored in a content area within the Exact Target interface. To do this, you will need to create an HTML content area and place the following within it:

    [code]%%before;httpget;1"http://domain.com/rss"%%%5B/code%5D

    This piece of code will fetch the contents of the RSS feed each time the content area is called.

    For example, when we use ContentAreaByName("My Contentsrss_featured"), the RSS is being fetched and stored at that time.

    Parse the RSS Contents

    Actually parsing the RSS feed and getting the desired output was a bit more difficult since Exact Target uses what I believe is a proprietary language named AMPscript.

    Thankfully, the Exact Target support came through with a snippet of code that gave me a good head start. I took that snippet and built the following.

    [code]
    %%[
    Var @xml, @titles, @title, @descs, @desc, @links, @link, @cnt, @dates, @date
    Set @xml = ContentAreaByName("My Contentsrss_featured") /* This line specifies the content area from which the RSS content will be pulled for the email message. */
    Set @titles = BuildRowsetFromXML(@xml,"//item/title",1)
    Set @descs = BuildRowsetFromXML(@xml,"//item/description",1)
    Set @links = BuildRowsetFromXML(@xml,"//item/link",1)
    Set @dates = BuildRowsetFromXML(@xml, "//item/pubDate", 1)

    If RowCount(@titles) > 5 THEN
    SET @rows = 5
    ELSE
    SET @rows = RowCount(@titles)
    ENDIF

    IF @rows >= 1 THEN
    for @cnt = 1 to @rows do
    Set @title = Field(Row(@titles,@cnt),"Value")
    Set @desc = Field(Row(@descs,@cnt), "Value")
    Set @link = Field(Row(@links,@cnt), "Value")
    Set @date = Format(DateParse(Field(Row(@dates,@cnt), "Value")),"MMM d, yyyy h:mm tt")
    ]%%

    <div class="feed-item" style="background:#444;padding:10px 10px 0;margin-bottom:20px;border-left:4px solid #222;"><span style="color:#ffffff;font-size:16px;line-height:20px;margin-bottom:12px;">%%=v(@title)=%%</span>
    <span style="color:#cccccc;font-size:12px;line-height:20px;margin-bottom:12px;">%%=v(@date)=%%</span>
    <a style="text-decoration:underline;font-weight:normal;color:#336699 !important;" href="%%=RedirectTo(@link)=%%">More info…</a>
    </div>

    %%[
    NEXT @cnt
    ENDIF
    ]%%
    [/code]

    This snippet pulls out the Title, Description, Link, and Publication Date for each item in an RSS feed and puts it into what I consider to be an array.

    The next is to then loop through these items, up to 5 rows worth, and get each value. Once we have these values stored in variables we can then place them in templates using the following syntax: %%=v(@varName)=%%.

    The biggest caveat in displaying the information was with inserting a link into the template. Notice that in the above example, %%=RedirectTo(@link)=%%, there is an extra call to RedirectTo. This has to do with the tracking system that Exact Target uses.

    Questions?

    This short article is meant as an introduction into how to parse RSS with Exact Target. I hope that this answers any questions you may have, but if you’d like more information, please leave a comment below and I’ll be sure to help you out.

  • Github Two-Factor Authentication Failed For HTTPS

    About two months ago I first switched to GitHub’s two-factor authentication. Later that day, when I went to push for the first, I had an authentication error and my push failed. I didn’t want to mess with the configuration that day, so I decided to turn off two-factor authentication on GitHub.

    Another Go at Two-Factor Authentication on GitHub

    After a new career move forced that I lock down my computer and my online identities like Fort Knox, I had no choice but to figure out how to get GitHub two-factor authentication working. Yet again, after I configured two-factor authentication on GitHub I had issues pulling from private repositories and pushing/pulling to any repository. So, after digging into the GitHub two-factor authentication blog post on GitHub, I came across this:

    If you are using SSH for Git authentication, rest easy: you don’t need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your application settings page.

    The Solution is Simple

    (more…)

  • Modifying Tribe Events Calendar Events List Widget

    While I have been generally happy with the plugin, I was not impressed with the lack of options that come with the events list widget.

    Also, the widget only shows the title of the event and the date directly below.

    But, You Can Extend the Events List Widget!

    After digging through code for The Events Calendar plugin, I found that the view (controls the display) for the widget is located in /views/widgets/list-widget.php.

    Here is the source code for that file — taken from the WordPress.org repo on 5-16-2014 :

    <?php
    /**
     * Events List Widget Template
     * This is the template for the output of the events list widget.
     * All the items are turned on and off through the widget admin.
     * There is currently no default styling, which is needed.
     *
     * This view contains the filters required to create an effective events list widget view.
     *
     * You can recreate an ENTIRELY new events list widget view by doing a template override,
     * and placing a list-widget.php file in a tribe-events/widgets/ directory
     * within your theme directory, which will override the /views/widgets/list-widget.php.
     *
     * You can use any or all filters included in this file or create your own filters in
     * your functions.php. In order to modify or extend a single filter, please see our
     * readme on templates hooks and filters (TO-DO)
     *
     * @return string
     *
     * @package TribeEventsCalendar
     * @since  2.1
     * @author Modern Tribe Inc.
     *
     */
    ?>
    
    <li class="tribe-events-list-widget-events <?php tribe_events_event_classes() ?>">
    
        <?php do_action( 'tribe_events_list_widget_before_the_event_title' ); ?>
    
        <h4 class="entry-title summary">
                <a href="<?php echo tribe_get_event_link(); ?>" rel="bookmark"><?php the_title(); ?></a>
        </h4>
    
        <?php do_action( 'tribe_events_list_widget_after_the_event_title' ); ?>
        <!-- Event Time -->
    
        <?php do_action( 'tribe_events_list_widget_before_the_meta' ) ?>
    
        <div class="duration">
            <?php echo tribe_events_event_schedule_details(); ?>
        </div>
    
        <?php do_action( 'tribe_events_list_widget_before_the_meta' ) ?>
    
        <!-- Event Title -->
    </li>

    First things first, always read the comments! After reading the comments in this file, I became aware that there are two ways to update the events list widget:

    • Create a completely new template
    • Use actions in the functions.php of a theme or in a separate plugin

    For my purposes, I only wanted to add a description to each listing, so I decided to just use the actions.

    But, if you need a completely new look, you could create a new template file in your theme directory at THEME_DIR/tribe-events/widgets/list-widget.php .

    Adding a Description with Actions

    Because all I wanted to do was add a description below the date for each event in the events list widget, my solution was pretty simple.

    add_action( 'tribe_events_list_widget_after_the_meta', 'edit_tribe_widget_after_title' );
    function edit_tribe_widget_after_title() {
        global $post;
        $event = $post;
    
        echo wpautop( wp_trim_words( $post->post_content, 12, '&hellip; <a href=' . get_permalink( $event ) . '>Read&nbsp;More &rarr;</a>' ) );
    }

    This snippet will tie into the action that fires right after the meta in each event item, and it will insert up to 12 words of the description for each event as well as a read more link.

    While I hooked into the after_meta action to add a description, you could easily use one of these other actions to modify the events list widget to your needs:

    • tribe_events_list_widget_before_the_event_title
    • tribe_events_list_widget_after_the_event_title
    • tribe_events_list_widget_before_the_meta
    • tribe_events_list_widget_before_the_meta

    Because the widget calls tribe_events_event_schedule_details(), you can also use the the tribe_events_event_schedule_details filter to filter what shows up in the meta section.

    Questions, Comments, Bugs?

    First, there is a bug on line 44 of this plugin (bonus if you can figure out what it is). I checked the GitHub repository and they had already fixed it, it just hasn’t been pushed to the WordPress repository.

    If there are any other questions or comments, please leave a comment below. If you see any other bugs than the one mentioned above, please leave a comment below so I can fix it 🙂

  • Regular Expression Example: Wrapping the Second through Last Words in a Span Element

    For the past week, I have been working on a website for an emergency medical services association. To fit the client’s wishes, the design called for the first word in titles to be blue followed by all other words being red.

    I do not know a way to do this with just HTML, so I decided that I would wrap the second through the last words in a span  element. Then I could add some LESS like this to achieve the color effect I wanted.

    [code lang=css]
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
    color: blue;

    span {
    color: red;
    }
    }
    [/code]

    But, how do I get the span element in the titles?

    Using Regular Expressions to Add the Span

    Regular expressions are a very powerful feature of many languages. They allow us to create very complex rules to match phrases in code, words, etc. We can also “capture” parts of these rules, which will prove useful in this example!

    Here is a PHP function with a regular expression example that takes a title and wraps the second through last words in a span  element.

    [code lang=php]
    function span_the_title( $title ) {
    return preg_replace( '#(S+)s(.+)#', '$1 <span>$2</span>', $title );
    }
    [/code]

    Let’s break this down. Notice that I am passing $title in to the function. This is the title that we will actually be filtering in the regular expression. Now take a look at the preg_replace() function. This function takes the following arguments:

    1. A regular expression that is the pattern to search for.
    2. A string to replace matched expressions with. Notice how I used $1 and $2 in the second argument above. This is because I am referencing part of the matched regular expression from the first argument. More on this later.
    3. The third argument is the title, in this case, or really any string.

    Let’s Break It Down

    (more…)