Jump to content

Expressions Pattern


SaeedGh

Recommended Posts

Hi

excuse me, if my string is "1[2]3" how i can write an expressions pattern to replace "1" and "3" by "x".

i want this result: "x[2]x"

 

for example i tried to change "I see [saeed] at home!" to "xxxxxx[saeed]xxxxxxxxx"

 

$text = preg_replace('/[^\[(.*)\]]/', "x", $text);

 

not work!  :-\

Thank you.

Link to comment
Share on other sites

While I'm working on the solution, I can tell you why your expression is not working. Whenever you use a wildcard metacharacter '.' inside a character class [ ], the wildcard is no longer a metacharacter.. so it becomes literally a period. The same thing applies to any would-be metacharacter (such as *+?).

 

Cheers,

 

NRG

Link to comment
Share on other sites

Ok.. it's not necessarily pretty, but it seems to work:

 

$str = "I see [saeed] at home!";
echo $str . '<br />';
$newSTR = split(' ', $str);
for($i = 0, $total = count($newSTR); $i < $total; $i++){
   if(!preg_match('#(\[|\])#', $newSTR[$i])){
      $newSTR[$i] = preg_replace('#.+#U', 'x', $newSTR[$i]);
   }
}

$finalSTR = implode('x', $newSTR);
echo $finalSTR;

 

I'm sure there is a much more elegant solution, but given my limited knowledge, this is what I came up with.

 

Cheers,

 

NRG

Link to comment
Share on other sites

<pre>
<?php
$tests = array(
	'1[2]3',
	'I see [saeed] at home!'
);
foreach ($tests as $test) {
	echo "$test => ";
	echo preg_replace('/
		\A
		(.*?)
		(\[[^\]]*\])
		(.*)
		\z
	/ex', '
		str_repeat("x", strlen("$1")) .
		"$2" .
		str_repeat("x", strlen("$3"))
	', $test);
	echo '<br>';
}
?> 
</pre>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.