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
https://forums.phpfreaks.com/topic/120444-expressions-pattern/
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
https://forums.phpfreaks.com/topic/120444-expressions-pattern/#findComment-620920
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
https://forums.phpfreaks.com/topic/120444-expressions-pattern/#findComment-620947
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
https://forums.phpfreaks.com/topic/120444-expressions-pattern/#findComment-621113
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.