I am using some ready-made code and it was using implode & explode functions to assign tags to photos, tags users typed in. It was not doing it right though, as if you tried a two word tag, it was splitting it. So I replaced the explode function with a preg_split function with a regex I found, but even though testing the function & regex on http://php.fnlist.com/regexp/preg_split shows that it splits the tags correctly, in my application it totally ignores any two-word tags.
I am trying to get, from input like "crime, love, mystery ,crime drama,romance" nicely formatted tags: "crime,love,mystery,crime drama,romance" and I get instead: "crime, love, mystery,romance"
I am giving the code I have below. Please help!!
<?php
class PhotoTagsController extends AppController {
var $name = 'PhotoTags';
var $uses = array('PhotoTag', 'Photo');
function edit($id = null)
{
$this->authorize();
if(!($photo = $this->Photo->findById($id)))
{
$this->flash('error', ucfirst(i18n::translate('photo not found')));
$this->redirect('/');
}
else
{
$this->authorize($photo['Photo']['user_id']);
$this->set('photo', $photo);
if(empty($this->data))
{
$photo['Photo']['tags'] = array();
foreach($photo['PhotoTag'] as $tag)
$photo['Photo']['tags'][] = $tag['tag'];
$photo['Photo']['tags'] = implode(',', $photo['Photo']['tags']);
$this->data = $photo;
}
else
{
// foreach(explode(',', $this->data['Photo']['tags']) as $tag)
foreach(preg_split("/[s]*[,][ s]*/", $this->data['Photo']['tags']) as $tag)
{
$tag = strtolower(rtrim($tag)); //trims whitespace at end of tag
if(!empty($tag))
{
$found = false;
for($i = 0; $i < count($photo['PhotoTag']); $i++)
{
if(isset($photo['PhotoTag'][$i]) && $photo['PhotoTag'][$i]['tag'] == $tag)
{
$found = true;
unset($photo['PhotoTag'][$i]);
break;
}
}
if(!$found)
{
$this->PhotoTag->create();
$this->PhotoTag->save(array('PhotoTag' => array('photo_id' => $photo['Photo']['id'], 'tag' => $tag)));
}
}
}
foreach($photo['PhotoTag'] as $tag)
$this->PhotoTag->delete($tag['id']);
$this->flash('valid', ucfirst(i18n::translate('tags changed')));
$this->redirect('/photos/show/' . $photo['User']['username'] . '/' . $photo['Photo']['id']);
}
}
}
function ajax_edit($id = null) {
$this->authorize();
if(!($photo = $this->Photo->findById($id)))
{
die();
}
else
{
$this->authorize($photo['Photo']['user_id']);
// foreach(explode(',', $this->params['form']['value']) as $tag)
foreach(preg_split("/[s]*[,][ s]*/", $this->params['form']['value']) as $tag)
{
$tag = strtolower(rtrim($tag));
if(!empty($tag))
{
$found = false;
for($i = 0; $i < count($photo['PhotoTag']); $i++)
{
if(isset($photo['PhotoTag'][$i]) && $photo['PhotoTag'][$i]['tag'] == $tag)
{
$found = true;
unset($photo['PhotoTag'][$i]);
break;
}
}
if(!$found)
{
$this->PhotoTag->create();
$this->PhotoTag->save(array('PhotoTag' => array('photo_id' => $photo['Photo']['id'], 'tag' => $tag)));
}
}
}
foreach($photo['PhotoTag'] as $tag)
$this->PhotoTag->delete($tag['id']);
echo $this->params['form']['value'];
die();
}
}
}
?>