We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 21872
    • 95 Posts
    I know this isn’t really the place to learn PHP, but this should be simple, I think. There’s a Wordpress plugin called Widon’t that’s been ported to a number of CMS. The heart of it is this:
    preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1 $2', $str);


    It is supposed to replace the space between the last two words of a string with a   The help doc at http://svn.modxcms.com/docs/display/revolution/Plugins gives this example of text parsing:
    $words = array("snippet", "template"); // words to filter
    $output = &$modx->resource->_output; // get a reference to the output
    $output = str_replace($words,"<b>[filtered]</b>",$output);
    

    And says to register it with the OnWebPagePrerender event. By analogy, then, I thought something like this:
    $output = &$modx->resource->_output;
    $output = preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1 $2', $output);

    would do the trick, but it doesn’t.

    Would someone please tell me why it doesn’t and what will?
      • 22303 MODX Staff
      • 10,725 Posts
      That should work, though to make it even simpler:
      <?php
      $modx->resource->_output = preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1 $2', $modx->resource->_output);
      ?>

      Did you clear your cache after making the changes to the plugin? The plugin will not get registered in a Context until that Context’s cache is cleared. Also, this will not work on binary Content Types, but that should be obvious.
        • 21872
        • 95 Posts
        Thank you, you were correct that it worked. Looking closer I found the real culprit, the plugin works but the regular expression isn’t specific enough. It treats the entire page as a string, not the content of individual elements. Checking the source, I found this:
        </body> </html>
        which I should have noticed sooner.

        I need some way to tell it to restrict itself to the contents of specific elements. I have no idea how to do that and would very much appreciate any pointers. Does PHP do DOM parsing or would I have to figure out what’s what with regular expressions?