0

I have an issue with triming a field before it is saved. I wanted to use substr(), or regex() with preg_match(). I have built a Drupal 7 module, but it can't work at all. I have tried using the trim plugin in feeds tamper module, but it doesn't seem to work. The data I am using is from a feed from Google Alerts. I have posted this issue here.

This is what I have done so far, and I know my regular expression is wrong; I was trying to get it do anything, just to see if I could get it to work, but I am pretty lost on how to add this type of function to a Drupal module.

function sub_node_save() {    
   $url = $node->field_web_screenhot['und'][0]['url'];
   $url = preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i',$url );
   $node->field_web_screenhot['und'][0]['url'] =$url;

  return ;
}

I used the Devel module to get the field.

If there's an easy way to use substr(), I would consider that or something else.

Basically, I just want to take the Google redirect off the URL, so it is just the basic URL to the web site.

4

1 回答 1

1

根据您的问题和后来的评论,我建议为此使用 node_presave hook (http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7)。它在插入(新)和更新操作之前调用,因此如果需要,您将需要额外的验证以防止它在节点更新上执行。

<?php
function MYMODULE_node_presave($node) {
// check if nodetype is "mytype"
    if ($node->type == 'mytype'){
        // PHP's parse_url to get params set to an array.
        $parts = parse_url($node->field_web_screenhot['und'][0]['url']); 
        // Now we explode the params by "&" to get the URL.
        $queryParts = explode('&', $parts['query']);

        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        } 
        //valid_url validates the URL (duh!), urldecode() makes the URL an actual one with fixing "//" in http, q is from the URL you provided.
        if (valid_url(urldecode($parms['q']))){
            $node->field_web_screenhot['und'][0]['url'] = urldecode($parms['q']);
        }
    }
}
于 2012-05-29T22:00:42.333 回答