1

次の文字列があります

someText 50-90% someText

文字列がこのような形式であっ%た場合の後に追加したいだけです50

someText 50%-90% someText

私は次のことを試しました...

preg_replace('/(\d+)\-[\d]+%/','$0%',  'text 30-50% text')
//the output: text 30-50%% text
preg_match_all('/(\d+)\-[\d]+%/',  'text 30-50% text',$x)
/*$x = array(2) {
*  [0]=>
*  array(1) {
*    [0]=>
*    string(6) "30-50%"
*  }
*  [1]=>
*  array(1) {
*    [0]=>
*    string(2) "30"
*  }
*}
*/
preg_replace('/(\d+)\-[\d]+%/','$1%',  'text 30-50% text');
//the output: text 30% text
4

4 に答える 4

3
<?php
function normalizeRange($range) {
    return preg_replace('~(\d+)(-\d+%)~','$1%$2', $range);
}

var_dump(normalizeRange("5-6%")); // 5%-6%
var_dump(normalizeRange("5%-6%")); // 5%-6%
于 2012-09-25T05:58:22.523 に答える
3

使用する:

$str = "someText 50-90% someText";

$ret = preg_replace('/\d+(?=-)/', '$0%', $str);

// if you want to more specifically
$ret = preg_replace('/\d+(?=-\d+%)/', '$0%', $str);
于 2012-09-25T05:58:33.963 に答える
1

これを試して:

<?php
$text = 'someText 50-90% someText';
// match all text like 50-90%, 6-10% etc
preg_match( '/(^[^\d]*)(\d*\-\d*\%)(.*)/', $text, $matches );
$matches[2] = str_replace( '-', '%-', $matches[2] );
array_shift( $matches );
$text = implode( '', $matches );
?>

お役に立てれば。

于 2012-09-25T06:13:30.560 に答える
1

使用する

$str    = 'text 30%-50% text';
echo preg_replace('/([\d]+)\-[\d]+%/','$1%',  $str);
于 2012-09-25T06:04:32.243 に答える