问题
I am running a Wordpress site and using WPML translation plugin. In WPML there is a method called icl_link_to_element(2880);
that returns and generates the following element in the DOM:
<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>
I want to convert this element to a string so that I can simply return and store the last part of the url atencion-al-cliente
, into a unique variable.
What's the best way to get this done?
Answer to the comment below:
Two elements appear in the DOM now.
<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>
and
"NULL
"
回答1:
First do the following steps to get that URL
$page = icl_object_id(2880, 'page', true);
$url = get_permalink($page);
Then use $parts = explode("/", $url)
function and get the last element of that array, you can use array_pop()
回答2:
Use preg_match
to get the value of href, Now get the matched value using parse_url
, after getting just collect the path from the return array.
Now its time to get the last portion of the url, So try this below code.
$html = '<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>';
preg_match('/<a href="(.+)">/', $html, $match);
$info = parse_url($match[1]);
$str = $info['path'];
$len = strlen($info['path']);
echo trim(substr($str, strrpos($str, '/'), $len), "/"); //atencion-al-cliente
来源:https://stackoverflow.com/questions/37251703/converting-a-dom-element-into-a-string-in-php