2013-07-05 30 views
0

我试图找到最佳方式来抓住动态子字符串,但替换后的所有内容。试图抓住一个字符串与一个子字符串静态和一个动态

这就是我想要实现:

{table_telecommunications}

的子{table_始终是一样的,只是不同是telecommunications}

我想抓住电信这个词,所以我可以在MySQL表上进行搜索,然后用返回的内容替换{table_telecommunications}

我想制作一个strpos然后explode等等。

但我想用正则表达式会更容易,但我没有创建正则表达式的技能。

你能否给我最好的方法来做到这一点?

编辑:我说可能正则表达式是最好的方式bcuz我需要找到在这个格式字符串,但第二部分是可变的,就像{table_*}

回答

1

使用正则表达式。

<?php 
    $string = "{table_telecommunications} blabla blabla {table_block}"; 
    preg_match_all("/\{table_(.+?)\}/is", $string, $matches); 
    $substrings = $matches[1]; 

    print_r($substrings); 
?> 
+0

如果我的字符串是'{} table_telecommunications布拉布拉布拉布拉{table_block}',该阵列的比赛将只包含'[ '{} table_telecommunications', '电信']'.. 。 – silentw

+0

@silentw,编辑支持多个子字符串。 – Nadh

+0

非常感谢,正是我需要的! – silentw

0
$input = '{table_telecommunications}'; 
$table_name = trim(implode('_', array_shift(explode($input, '_'))), '}'); 

要快,无需正则表达式。

1
if (preg_match('#table_([^}]+)}#', '{table_telecommunications}', $matches)){ 
    echo $matches[1]; 
} 

这是一个正则表达式解决方案。你可以做爆炸一样:

$parts = explode('table_', '{table_telecommunications}'); 
echo substr($parts[1], 0, -1); 
+0

我只想抓住以{{table_'开头的那个,你可以编辑你的答案,以便它符合我的需求? – silentw

+0

当然。得到它编辑。 –