Search code examples
phpregexsearchpreg-match-allpartial

php get css class and assign it to rel attribute


How do I take this:

<img class="classone twoclass alignLEFT" src="xxxx" />

search for the word "align" in the class array, take the remainder of the word "align" (in this case "left") and assign it to an actual align property?

<img class="classone twoclass alignLEFT" align="LEFT" src="xxxx" />

I know I need

$needle = "align";
$haystack = "<img class="classone twoclass alignLEFT" src="xxxx" />"

and what I'm looking for is

$pincushion = {{the rest of the word from $needle}}

so basically I'm doing a preg_match for $needle. If found, how do I get the rest of that word (i.e., $pincushion) ?

I tried preg_split but it wouldn't allow me to use "align" as a delimiter. (makes sense)

This can NOT be jquery / javascript - it must take place in the rendered html code.

Any thoughts? I've spent 10 hours now searching for an answer with no real luck. I did come across DomDocument but couldn't make that find what I needed either.


Solution

  • preg_match_all('#align(.*?)(" )#si', '<img class="classone twoclass alignLEFT" src="xxxx" />', $arr, PREG_PATTERN_ORDER);
    

    Result:

    Array
    (
    [0] => Array
        (
            [0] => alignLEFT" 
        )
    
    [1] => Array
        (
            [0] => LEFT
        )
    
    [2] => Array
        (
            [0] => " 
        )
    
    )
    

    Explaination: #align(.*?)(" )#si looks for algin followed by n-chars delimited by " or .