tags:

views:

33

answers:

2

guys i have arrays in which i have to match this kind of text then remove spaces in-between the words ,

 Name:'lofse erbbnwq qweqw-qweqw' KKK
 Name:'lofsdsse erbsdsdbnwq sds sdsd sdqwsdseqw-qwsdseqw' KKK
 Name:'lofsse esdsdbnwq sds sds sddseqw-qwseqw' KKK



 i read somewhere that it will work like this, but i tried and its not working :(

$data = preg_replace_callback('%Name:\'(.*)\' kkk%',replace_within_tag, $data);
function replace_within_tag($groups) {return preg_replace('/\s/', '.', $groups[0]);}

output should be like this

 Name:'lofse.erbbnwq.qweqw-qweqw' KKK
 Name:'lofsdsse.erbsdsdbnwq.sds.sdsd.sdqwsdseqw-qwsdseqw' KKK
 Name:'lofsse.esdsdbnwq.sds.sds.sddseqw-qwseqw' KKK

please i need some quick help on this, just tell me the working way

A: 

Group the match and then use $matches[1] in the callback to only replace spaces in the part of the text between the quotes. You have a couple of ways of doing this. For example:

$output = preg_replace_callback("!(Name:')(.*?)(' KKK)!", 'replace_spaces', $input);

function replace_spaces($matches) {
  return $matches[1] . preg_replace('!\s+!', '.', $matches[2]) . $matches[3];
}

You need to do this because you're capturing the leading and trailing strings. An alternative way is to capture less. For example:

$output = preg_replace_callback("!(?<=').*?(?=')!", 'replace_spaces', $input);

function replace_spaces($matches) {
  return preg_replace('!\s+!', '.', $matches[0]);
}

This is using lookaheads and lookbehinds.

cletus
worked, thanks :D
Jake
output is like lofse.erbbnwq.qweqw-qweqw, removes the name and kkk, but its working for me :D
Jake
+1  A: 
$array=array("Name:'lofse erbbnwq qweqw-qweqw' KKK", "Name:'lofsdsse erbsdsdbnwq sds sdsd sdqwsdseqw-qwsdseqw' KKK","Name:'lofsse esdsdbnwq sds sds sddseqw-qwseqw' KKK");
foreach ($array as $k=>$v){
  if ( strpos($v,"Name:" ) !==FALSE) {
        $s = explode("'",$v);
        $s[1]=preg_replace("/\s+/",".",$s[1]);
        $array[$k]=implode("'",$s);
  }
}
print_r($array);

output

$ php test.php
Array
(
    [0] => Name:'lofse.erbbnwq.qweqw-qweqw' KKK
    [1] => Name:'lofsdsse.erbsdsdbnwq.sds.sdsd.sdqwsdseqw-qwsdseqw' KKK
    [2] => Name:'lofsse.esdsdbnwq.sds.sds.sddseqw-qwseqw' KKK
)
ghostdog74
dont u think its a bit long way to do that task ?
Jake
no, looks fine to me.
ghostdog74