【问题标题】:parsing using php使用 php 解析
【发布时间】:2011-06-29 08:12:41
【问题描述】:

给定一个字符串:

[[Pulsatile_flow|pulsatile]] 血流的性质产生脉搏 向下传播的波 [[动脉树]],并在 [[Aortic_bifurcation|分叉]] 反射波反弹返回 半月瓣及其起源 [[主动脉]]。这些返回波产生 这 [[Dicrotic_notch#Ventricular_systole|dicrotic notch]] 显示在主动脉中 [[心脏期间的压力曲线 循环]] 当这些反射波推动 在[[心脏瓣膜|主动脉半月 阀门]].[[维基词典:主动脉|]]

我如何提取包含在 '[[ ]]' 中的所有单词/短语,然后使用 php 将其放入数组中。

有条件: 如果“|”存在仅检索“|”之后的单词如果 "|" 后不存在任何单词检索“|”之前的单词但在“:”之后。
括号中的单词也将被忽略。

例子

[[aorta]]                              => retrieve aortal

[[Pulsatile_flow|pulsatile]]           => retrieve only pulsatile

[[Pulsatile_flow|pulsatile (temp)]]    => retrieve only pulsatile

[[Wiktionary:aorta|Aorta Topic]]       => retrieve Aorta Topic

[[Wiktionary:aorta|]]                  => retrieve aorta

[[aorta|]]                             => retrieve aorta

如果“|”不存在检索全部

 [[Wiktionary:aorta]]  => retrieve Wiktionary:aorta

【问题讨论】:

  • 请注意,如果您尝试解析 Wikipedia,由于模板、表格等原因,它会变得更加困难。解析他们的静态 HTML 转储文件可能会更好。

标签: php extract wikipedia


【解决方案1】:

看看这个:

$results = array();
$source = "The [[Pulsatile_flow|pulsatile]] nature of blood flow creates a pulse wave that is propagated down the [[arterial tree]], and at [[Aortic_bifurcation|bifurcations]] reflected waves rebound to return to semilunar valves and the origin of the [[aorta]]. These return waves create the [[Dicrotic_notch#Ventricular_systole|dicrotic notch]] displayed in the aortic pressure curve during the [[cardiac cycle]] as these reflected waves push on the [[heart valve|aortic semilunar valve]].[[Wiktionary:aorta|]]";
if ( preg_match_all('/\[\[(.*?)\]\]/is', $source, $matches) ) 
{
    foreach ( $matches[1] as $match ) 
    {
        if ( strpos( $match, '|' ) === false ) {
            $results[] = $match;
        } else {
            $parts = explode( '|', $match );
            if ( empty( $parts[1] ) ) {
                $parts = explode( ':', $parts[0] );
                $results[] = count( $parts ) == 2 ? $parts[1] : $parts[0];
            } else {
                $results[] = preg_replace( '/\(.*?\)/is', '', $parts[1] );
            }
        }
    }
}

var_dump( $results );

【讨论】:

  • +1。只要您不需要围绕[[]] 设置太多规则,例如转义、嵌套等,正则表达式就是一个很好的解决方案。
猜你喜欢
  • 2010-11-10
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 2018-01-27
  • 2018-05-14
  • 2016-04-24
  • 2021-10-26
相关资源
最近更新 更多